var AWS = {
  replacebr: function(html) {
    return html.replace(/\n/g, "<br/>").replace(/\r/g, "<br/>");
  },
  tips: function(type, data, callback) {
    if (type == "success") {
      var template = Hogan.compile($("#template-tips-success").html()).render({
        tips: data ? data : "操作成功"
      });
    } else if (type == "error") {
      var template = $("#template-tips-error")
        .html()
        .replace("{{message}}", data);
    }

    if ($(".alert-box").length) {
      $(".alert-box").remove();
    }

    $("#aw-ajax-box")
      .html(template)
      .show();

    $(".modal").modal("show");

    if (type == "success") {
      setTimeout(function() {
        $(".modal").modal("hide");

        if (callback) {
          callback();
        }
      }, 1000);
    } else {
      if (callback) {
        callback();
      }
    }
  },
  getQueryByName: function(name, url) {
    if (!url) url = window.location.href;
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
    var results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return "";
    return decodeURIComponent(results[2].replace(/\+/g, " "));
  },
  // 获取url里的id，仅限这种url: survey2/2?name=xxx (获取id 2)
  getUrlId: function() {
    return window.location.pathname.split("/")[
      window.location.pathname.split("/").length - 1
    ];
  },
  global_tips: function(type, callback) {
    if (!$("#aw-ajax-box")) {
      return false;
    }

    var tips;

    // notify_message_integral 积分
    if (type == "integral") {
      if ($.cookie(G_COOKIE_PREFIX + "notify_message_integral")) {
        var data = eval(
          "(" + $.cookie(G_COOKIE_PREFIX + "notify_message_integral") + ")"
        );

        tips = data.message + " 积分<span>" + data.integral + "</span>";
      }
    } else if (type == "message_exp") {
      // notify_message_exp 经验
      if ($.cookie(G_COOKIE_PREFIX + "notify_message_exp")) {
        var data = eval(
          "(" + $.cookie(G_COOKIE_PREFIX + "notify_message_exp") + ")"
        );

        tips = data.message + " <span>" + data.rank + "</span>";
      }
    }

    if (tips) {
      var template = AW_TEMPLATE.globalTipsBox.replace("{{tips}}", tips);

      if ($(".alert-box").length) {
        $(".alert-box").remove();
      }

      $("#aw-ajax-box")
        .html(template)
        .show();

      $(".modal").modal({
        show: true,
        backdrop: false
      });

      setTimeout(function() {
        $(".modal").modal("hide");

        if (type == "integral") {
          // 积分
          $.get(
            G_BASE_URL + "/account/ajax/remove_notify_message_cookie/integral",
            function() {}
          );
        } else if (type == "message_exp") {
          // notify_message_exp 经验
          $.get(
            G_BASE_URL + "/account/ajax/remove_notify_message_cookie/exp",
            function() {}
          );
        }

        if (callback) {
          callback();
        }
      }, 1000);
    }
  },
  global_tips_redirect: function(tips, url) {
    var template = AW_TEMPLATE.globalTipsBox.replace("{{tips}}", tips);

    if ($(".alert-box").length) {
      $(".alert-box").remove();
    }

    $("#aw-ajax-box")
      .html(template)
      .show();

    $(".modal").modal({
      show: true,
      backdrop: false
    });

    setTimeout(function() {
      window.location.href = url;
    }, 2000);
  },
  //全局loading
  loading: function(type, fullscreen) {
    if (!$("#aw-loading").length) {
      $("#aw-ajax-box").append(AW_TEMPLATE.loadingBox);
    }

    if (fullscreen) {
      $("#aw-ajax-box").append('<div class="modal-backdrop fade in"></div>');
    }

    if (type == "show") {
      if ($("#aw-loading").css("display") == "block") {
        return false;
      }

      $("#aw-loading").fadeIn();

      AWS.G.loading_timer = setInterval(function() {
        AWS.G.loading_bg_count++;

        $("#aw-loading-box").css(
          "background-position",
          "0px " + AWS.G.loading_bg_count * -70 + "px"
        );

        if (AWS.G.loading_bg_count == 22) {
          AWS.G.loading_bg_count = 0;
        }
      }, 100);
    } else {
      $("#aw-loading").fadeOut();

      if (fullscreen) {
        $(".modal-backdrop").detach();
      }

      clearInterval(AWS.G.loading_timer);
    }
  },

  // 格式化日期时间戳
  format_date_time: function(inputTime) {
    var date = new Date(inputTime * 1000);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    month = month < 10 ? "0" + month : month;
    var day = date.getDate();
    day = day < 10 ? "0" + day : day;
    var hour = date.getHours();
    hour = hour < 10 ? "0" + hour : hour;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? "0" + minute : minute;
    second = second < 10 ? "0" + second : second;
    return year + "-" + month + "-" + day + " " + hour + ":" + minute;
  },
  // 时间友好型提示风格化
  date_friendly: function(timestamp) {
    var timeLimit = 604800;
    var timeSettings = {
      YEAR: "%s 年前",
      MONTH: "%s 月前",
      DAY: "%s 天前",
      HOUR: "%s 小时前",
      MINUTE: "%s 分钟前",
      SECOND: "%s 秒前"
    };
    var type;

    var timeNow = Math.floor(new Date().getTime() / 1000);
    var seconds = Math.abs(timestamp - timeNow);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);
    var days = Math.floor(hours / 24);
    var months = Math.floor(days / 30);
    var years = Math.floor(months / 12);

    if (seconds > timeLimit) {
      return AWS.format_date_time(timestamp);
    }

    if (years > 0) {
      type = "YEAR";
    } else {
      if (months > 0) {
        type = "MONTH";
      } else {
        if (days > 0) {
          type = "DAY";
        } else {
          if (hours > 0) {
            type = "HOUR";
          } else {
            type = minutes > 0 ? "MINUTE" : "SECOND";
          }
        }
      }
    }

    var timeDiff;

    switch (type) {
      case "YEAR":
        timeDiff = timeSettings[type].replace("%s", years);
        break;

      case "MONTH":
        timeDiff = timeSettings[type].replace("%s", months);
        break;

      case "DAY":
        timeDiff = timeSettings[type].replace("%s", days);
        break;

      case "HOUR":
        timeDiff = timeSettings[type].replace("%s", hours);
        break;

      case "MINUTE":
        timeDiff = timeSettings[type].replace("%s", minutes);
        break;

      case "SECOND":
        timeDiff = timeSettings[type].replace("%s", seconds);
        break;
    }

    return timeDiff;
  },

  countdown: function(endtime, el) {
    var now = new Date().getTime();
    var countdown_secs = parseInt((endtime * 1000 - now) / 1000);
    var days = Math.floor(countdown_secs / 86400);
    var hrs = Math.floor(countdown_secs / 3600);
    var mins_in_hr = Math.floor((countdown_secs - 3600 * hrs) / 60);
    var secs_in_min = countdown_secs - hrs * 3600 - mins_in_hr * 60;
    var end_flag = false;

    if (endtime * 1000 - now <= 0) {
      end_flag = true;
    }

    AWS.G.countdown = {
      days: days,
      hour: parseInt(hrs) < 10 ? "0" + hrs : hrs,
      min: parseInt(mins_in_hr) < 10 ? "0" + mins_in_hr : mins_in_hr,
      sec: parseInt(secs_in_min) < 10 ? "0" + secs_in_min : secs_in_min,
      end_flag: end_flag
    };

    if (el) {
      if (AWS.G.countdown.end_flag) {
        var template =
          '<div class="hour">00</div><span>:</span><div class="minutes">00 </div><span>:</span><div class="second">00</div>';
      } else if (AWS.G.countdown.hour < 100) {
        var template =
          '<div class="hour">' +
          AWS.G.countdown.hour +
          '</div><span>:</span><div class="minutes">' +
          AWS.G.countdown.min +
          '</div><span>:</span><div class="second">' +
          AWS.G.countdown.sec +
          "</div>";
      } else {
        var template =
          '剩<div class="hour">' + AWS.G.countdown.days + "</div>天";
      }

      el.html(template);
    }
  },

  ajax_request: function(url, params) {
    AWS.loading("show", true);

    if (params) {
      $.post(
        url,
        params + "&_post_type=ajax",
        function(result) {
          _callback(result);
        },
        "json"
      ).error(function(error) {
        _error(error);
      });
    } else {
      $.get(
        url,
        function(result) {
          _callback(result);
        },
        "json"
      ).error(function(error) {
        _error(error);
      });
    }

    function _callback(result) {
      AWS.loading("hide", true);

      if (!result) {
        return false;
      }

      if (result.err) {
        AWS.alert(result.err);
      } else if (result.rsm && result.rsm.url) {
        //window.location = decodeURIComponent(result.rsm.url);
        window.location = result.rsm.url;
      } else if (result.errno == 1) {
        window.location.reload();
      }
    }

    function _error(error) {
      AWS.loading("hide");

      if ($.trim(error.responseText) != "") {
        alert(_t("发生错误, 返回的信息:") + " " + error.responseText);
      }
    }

    return false;
  },

  ajax_post: function(
    formEl,
    processer,
    type // 表单对象，用 jQuery 获取，回调函数名
  ) {
    // 若有编辑器的话就更新编辑器内容再提交
    if (typeof CKEDITOR != "undefined") {
      for (instance in CKEDITOR.instances) {
        CKEDITOR.instances[instance].updateElement();
      }
    }

    if (typeof processer != "function") {
      var processer = AWS.ajax_processer;

      AWS.loading("show");
    }

    if (!type) {
      var type = "default";
    } else if (type == "reply") {
      AWS.loading("show");

      $(".btn-reply").addClass("disabled");
    } else if (type == "23andme") {
      $(".modal-backdrop")
        .removeClass("out, hide")
        .addClass("in");
    }

    var custom_data = {
      _post_type: "ajax"
    };

    formEl.ajaxSubmit({
      dataType: "json",
      data: custom_data,
      xhrFields: {
        withCredentials: true
      },
      crossDomain: true,
      success: function(result) {
        processer(type, result);
      },
      error: function(error) {
        if ($.trim(error.responseText) != "") {
          AWS.loading("hide");

          try {
            var obj = JSON.parse(error.responseText);
            if (typeof obj == "object" && obj) {
              AWS.alert(obj.err);
            } else {
              alert(_t("发生错误, 返回的信息:") + " " + error.responseText);
            }
          } catch (e) {
            alert(_t("发生错误, 返回的信息:") + " " + error.responseText);
          }
        }
      }
    });
  },

  // Modify by wecenter
  // ajax提交callback
  ajax_processer: function(type, result) {
    // 临时兼容重寄样本弹窗
    if (type == "refund_processer") {
      AWS.loading("hide");
    } else {
      if (
        type != "error_message" ||
        (type == "error_message" && result.errno == 1)
      ) {
        AWS.loading("hide", true);
      }
    }

    if (typeof result.errno == "undefined") {
      AWS.alert(result);
    } else if (result.errno != 1) {
      switch (type) {
        case "default":
        case "comments_form":
        case "reply":
          AWS.alert(result.err);

          $(".aw-comment-box-btn .btn-success, .btn-reply").removeClass(
            "disabled"
          );
          break;

        case "ajax_post_alert":
        case "ajax_post_modal":
        case "error_message":
        case "bind_control":
        case "refund_processer":
          if (!$(".error_message").length) {
            alert(result.err);
          } else if ($(".error_message em").length) {
            $(".error_message em").html(result.err);
          } else {
            $(".error_message").html(result.err);
          }

          if ($(".error_message").css("display") != "none") {
            AWS.shake($(".error_message"));
          } else {
            $(".error_message").fadeIn();
          }

          if ($("#captcha").length) {
            $("#captcha").click();
          }

          // 乳腺癌风险计算弹窗按钮
          if ($(".breast-cancer-box .btn").length) {
            $(".breast-cancer-box .btn")
              .html("提交")
              .removeClass("disabled");
          }
          break;

        // Modify by wecenter
        case "23andme":
          $(".modal-backdrop")
            .removeClass("in")
            .addClass("out hide");
          AWS.loading("hide");
          AWS.alert(result.err);
          break;
      }
    } else {
      if (type == "comments_form") {
        AWS.reload_comments_list(
          result.rsm.item_id,
          result.rsm.item_id,
          result.rsm.type_name
        );
        $(
          "#aw-comment-box-" +
            result.rsm.type_name +
            "-" +
            result.rsm.item_id +
            " form textarea"
        ).val("");
        $(
          "#aw-comment-box-" +
            result.rsm.type_name +
            "_answer" +
            "-" +
            result.rsm.item_id +
            " form textarea"
        ).val("");
        $(".aw-comment-box-btn .btn-success, .btn-reply").removeClass(
          "disabled"
        );
      }

      if (result.rsm && result.rsm.url) {
        // 判断返回url跟当前url是否相同
        if (window.location.href == result.rsm.url) {
          window.location.reload();
        } else {
          //window.location = decodeURIComponent(result.rsm.url);
          window.location = result.rsm.url;
        }
      } else {
        switch (type) {
          case "default":
          case "ajax_post_alert":
          case "error_message":
            window.location.reload();
            break;

          case "ajax_post_modal":
            $("#aw-ajax-box div.modal").modal("hide");
            break;

          // Modify by wecenter
          case "bind_control":
            bind_step(4);
            break;

          // 问题回复, 文章回复
          case "reply":
            AWS.loading("hide");

            if (result.rsm.ajax_html) {
              $(".aw-feed-list").append(result.rsm.ajax_html);

              $(".aw-comment-box-btn .btn-success, .btn-reply").removeClass(
                "disabled"
              );

              $.scrollTo($("#" + $(result.rsm.ajax_html).attr("id")), 600, {
                queue: true
              });

              // 文章
              $("#comment_editor").val("");

              // 问题
              $(".question_answer_form").detach();

              if ($(".aw-replay-box.question").length) {
                if (USER_ANSWERED) {
                  $(".aw-replay-box").append(
                    '<p align="center">一个问题只能回复一次, 你可以在发言后 ' +
                      ANSWER_EDIT_TIME +
                      " 分钟内编辑回复过的内容</p>"
                  );
                }
              }
            } else if (result.rsm.url) {
              //window.location = decodeURIComponent(result.rsm.url);
              window.location = result.rsm.url;
            } else {
              window.location.reload();
            }
            break;

          // Modify by wecenter
          case "23andme":
            $(".modal-backdrop")
              .removeClass("in")
              .addClass("out hide");
            AWS.loading("hide");
            break;

          // Modify by wecenter
          case "refund_processer":
          case "refund_processer":
            $("#request_form, .error_message").hide();
            $(".request-box .success").show();
            break;
        }
      }
    }
  },

  // 加载更多
  load_list_view: function(url, selector, container, start_page, callback) {
    if (!selector.attr("id")) {
      return false;
    }

    if (!start_page) {
      start_page = 0;
    }

    // 把页数绑定在元素上面
    if (selector.attr("data-page") == undefined) {
      selector.attr("data-page", start_page);
    } else {
      selector.attr("data-page", parseInt(selector.attr("data-page")) + 1);
    }

    selector.bind("click", function() {
      var _this = this;

      $(this).addClass("loading");

      $.get(url + "__page-" + $(_this).attr("data-page"), function(result) {
        $(_this).removeClass("loading");

        if ($.trim(result) != "") {
          if (
            $(_this).attr("data-page") == start_page &&
            $(_this).attr("auto-load") != "false"
          ) {
            container.html(result);
          } else {
            container.append(result);
          }

          // 页数增加1
          $(_this).attr("data-page", parseInt($(_this).attr("data-page")) + 1);
        } else {
          //没有内容
          if (
            $(_this).attr("data-page") == start_page &&
            $(_this).attr("auto-load") != "false"
          ) {
            container.html(
              '<p style="padding: 15px 0" align="center">' +
                _t("没有内容") +
                "</p>"
            );
          }

          $(_this)
            .addClass("disabled")
            .unbind("click")
            .bind("click", function() {
              return false;
            });

          $(_this)
            .find("span")
            .html(_t("没有更多了"));
        }

        if (callback != null) {
          callback();
        }
      });

      return false;
    });

    // 自动加载
    if (selector.attr("auto-load") != "false") {
      selector.click();
    }
  },

  // 重新加载评论列表
  reload_comments_list: function(item_id, element_id, type_name) {
    var url =
      G_BASE_URL +
      "/question/ajax/get_" +
      type_name +
      "_comments/" +
      type_name +
      "_id-" +
      item_id;

    if (type_name == "crowdsourcing") {
      url =
        G_BASE_URL +
        "/crowdsourcing/ajax/get_answer_comments/answer_id-" +
        item_id;
    }

    $(
      "#aw-comment-box-" + type_name + "-" + element_id + " .aw-comment-list"
    ).html(
      '<p align="center" class="aw-padding10"><i class="aw-loading"></i></p>'
    );

    $.get(url, function(data) {
      if (type_name == "crowdsourcing") {
        $(
          "#aw-comment-box-" +
            type_name +
            "_answer-" +
            element_id +
            " .aw-comment-list"
        ).html(data);
      } else {
        $(
          "#aw-comment-box-" +
            type_name +
            "-" +
            element_id +
            " .aw-comment-list"
        ).html(data);
      }
    });
  },

  // 警告弹窗
  alert: function(text, type, callback) {
    $(".alert-box").modal("hide");
    $(".modal-backdrop").detach();

    if ($("#aw-ajax-box .alert-box").length) {
      $("#aw-ajax-box .alert-box").remove();
    }

    if (type) {
      $("#aw-ajax-box").append(
        $("#template-tipsBox")
          .html()
          .replace("{{message}}", text)
      );
    } else {
      $("#aw-ajax-box").append(
        Hogan.compile($("#template-tipsBox").html()).render({
          message: text
        })
      );
    }
    $(".tips-box-sure-btn").click(function() {
      callback && callback();
      $(this).unbind("click");
    });
    $("#aw-ajax-box .alert-box").modal("show");
  },
  confirm: function(text, succCb, cancleCb) {
    $(".common-confirm-box").modal("hide");
    $(".modal-backdrop").detach();

    if ($("#aw-ajax-box .alert-box").length) {
      $("#aw-ajax-box .alert-box").remove();
    }

    $("#aw-ajax-box").append(
      Hogan.compile($("#template-commonConfirm").html()).render({
        message: text
      })
    );
    $(".confirm-box-cancel-btn").click(function() {
      cancleCb && cancleCb();
      $(this).unbind("click");
    });
    $(".confirm-box-sure-btn").click(function() {
      succCb && succCb();
      $(this).unbind("click");
    });
    $("#aw-ajax-box .alert-box").modal("show");
  },

  /**
   *	公共弹窗
   *	publish     : 发起
   *	redirect    : 问题重定向
   *	imageBox    : 插入图片
   *	videoBox    : 插入视频
   *  linkbox     : 插入链接
   *	commentEdit : 评论编辑
   *  favorite    : 评论添加收藏
   *	inbox       : 私信
   *  report      : 举报问题
   */
  dialog: function(type, data, callback) {
    switch (type) {
      // 微解读举报
      case "crowdsourcingInform":
        var template = Hogan.compile(
          $("#template-crowdsourcingInformBox").html()
        ).render();
        break;
      //赞赏列表
      case "crowdsourcingAward":
        var template = Hogan.compile(
          $("#template-crowdsourcingAward").html()
        ).render({
          costList: data.costList,
          title: data.title,
          rsm: data.rsm,
          userName: data.rsm.details.users[data.rsm.details.uid].user_name,
          avatarUrl: data.rsm.details.users[data.rsm.details.uid].avatar_url
        });
        break;
      //支付列表
      case "crowdsourcingPay":
        var template = Hogan.compile(
          $("#template-crowdsourcingPay").html()
        ).render({
          title: data.title,
          money: data.money,
          score: data.score,
          balance: data.balance,
          rate: data.rate * data.money,
          type: data.type
        });
        break;
      //支付
      case "crowdsourcingOrder":
        var template = Hogan.compile(
          $("#template-crowdsourcingOrder").html()
        ).render({
          title: data.title ? data.title : "提示信息",
          message: data.message
        });
        break;
      //提取收益
      case "crowdsourcingProfit":
        var template = Hogan.compile(
          $("#template-crowdsourcingProfit").html()
        ).render({
          title: data.title ? data.title : "提示信息",
          message: data.message
        });
        break;
      //赞赏列表
      case "crowdsourcingAwardList":
        var template = Hogan.compile(
          $("#template-crowdsourcingAwardList").html()
        ).render({
          list: data.list,
          count: data.count,
          userId: data.userId
        });

        break;
      case "tips":
        var template = $("#template-dialogTipsBox")
          .html()
          .replace("{{title}}", data.title)
          .replace("{{message}}", data.message);
        break;

      case "card":
        var template = Hogan.compile($("#template-cardTipsBox").html()).render({
          list: data.list,
          url: data.url
        });
        break;

      case "alertImg":
        var template = Hogan.compile($("#template-imgBox").html()).render({
          name: data.name,
          title: data.title ? data.title : "提示信息",
          hide: data.hide,
          url: data.url,
          message: data.message
        });
        break;

      case "publish":
        var template = Hogan.compile(AW_TEMPLATE.publishBox).render({
          category_id: data.category_id,
          ask_user_id: data.ask_user_id
        });
        break;

      case "redirect":
        var template = Hogan.compile(AW_TEMPLATE.questionRedirect).render({
          data_id: data
        });
        break;

      case "commentEdit":
        var template = Hogan.compile($("#template-commentBox").html()).render({
          answer_id: data.answer_id,
          attach_access_key: data.attach_access_key
        });
        break;

      case "favorite":
        var template = Hogan.compile(AW_TEMPLATE.favoriteBox).render({
          item_id: data.item_id,
          item_type: data.item_type
        });
        break;

      case "inbox":
        var template = Hogan.compile($("#template-inbox").html()).render({
          recipient: data,
          post_hash: G_POST_HASH ? G_POST_HASH : ""
        });
        break;

      case "report":
        var template = Hogan.compile($("#template-reportBox").html()).render({
          title: data.title,
          report_type: data.report_type,
          item_type: data.item_type,
          item_id: data.item_id
        });
        break;

      case "topicEditHistory":
        var template = AW_TEMPLATE.ajaxData
          .replace("{{title}}", _t("编辑记录"))
          .replace("{{data}}", data);
        break;

      case "ajaxData":
        var template = AW_TEMPLATE.ajaxData
          .replace("{{title}}", data.title)
          .replace("{{data}}", '<div id="aw_dialog_ajax_data"></div>');
        break;

      case "imagePreview":
        var template = AW_TEMPLATE.ajaxData
          .replace("{{title}}", data.title)
          .replace(
            "{{data}}",
            '<p align="center"><img src="' +
              data.image +
              '" alt="" style="max-width:520px" /></p>'
          );
        break;

      case "confirm":
        var template = Hogan.compile($("#template-confirmBox").html()).render({
          title: data.title ? data.title : "提示信息",
          message: data.message
        });
        break;

      case "recommend":
        var template = Hogan.compile(AW_TEMPLATE.recommend).render();
        break;

      // Modify by WeGene
      case "genodataReference":
        var template = Hogan.compile(
          $("#template-genodataReferenceBox").html()
        ).render({
          title: data.title
        });
        break;

      // Modify by WeGene
      case "refund":
        var template = Hogan.compile($("#template-refundBox").html()).render({
          title: data.title,
          barcode: data.barcode,
          user_info: data.user_info
        });
        break;

      case "resend":
        var template = Hogan.compile($("#template-resentBox").html()).render({
          title: data.title,
          barcode: data.barcode,
          user_info: data.user_info
        });
        break;

      // Modify by WeGene
      case "customerClient":
        var template = Hogan.compile(
          $("#template-customerClientBox").html()
        ).render({
          title: data.title
        });
        break;

      // Modify by WeGene
      case "dataDownload":
        var template = Hogan.compile($("#template-dataDownload").html()).render(
          {
            title: data.title,
            unique_id: data.unique_id
          }
        );
        break;

      // Modify by WeGene
      case "dataDownloadExtra":
        var template = Hogan.compile(
          $("#template-dataDownloadExtra").html()
        ).render({
          title: data.title,
          unique_id: data.unique_id
        });
        break;

      case "dataDownloadExtraTips":
        var template = Hogan.compile(
          $("#template-dataDownloadExtraTips").html()
        ).render({
          title: data.title
        });
        break;

      // 测序数据源下载
      case "dataDownloadRaw":
        var template = Hogan.compile(
          $("#template-dataDownloadRaw").html()
        ).render({
          title: data.title,
          unique_id: data.unique_id
        });
        break;

      // Modify by WeGene
      case "searchOriginBox":
        var template = Hogan.compile(
          $("#template-searchOriginBox").html()
        ).render({
          approved_symbol: data.approved_symbol,
          approved_name: data.approved_name,
          chromosome: data.chromosome,
          hgnc_id: data.hgnc_id,
          ensembl_gene_id: data.ensembl_gene_id,
          ccds_ids: data.ccds_ids,
          vega_id: data.vega_id,
          entrez_gene_id: data.entrez_gene_id,
          omim_id: data.omim_id,
          refseq: data.refseq,
          ucsc_id: data.ucsc_id,
          pubmed_ids: data.pubmed_ids,
          specialist_database_links: data.specialist_database_links
        });
        break;

      case "interpretBox":
        var template = Hogan.compile($("#template-interpretBox").html()).render(
          {
            title: "创建新项目"
          }
        );
        break;

      case "interpretAuthorityBox":
        var template = Hogan.compile(
          $("#template-interpretAuthorityBox").html()
        ).render({
          title: "授权许可"
        });
        break;

      case "interpretAuthorityProBox":
        var template = Hogan.compile(
          $("#template-interpretAuthorityBox").html()
        ).render({
          title: "授权许可"
        });
        break;

      case "researchSleepsBox":
        var template = Hogan.compile(
          $("#template-searchsleepsBox").html()
        ).render({
          title: "帮助及隐私说明"
        });
        break;

      case "researchNutritionBox":
        var template = Hogan.compile(
          $("#template-researchNutritionBox").html()
        ).render({
          title: "帮助及隐私说明"
        });
        break;

      // 报告结果反馈
      case "reportFeedbackBox":
        var template = Hogan.compile(
          $("#template-reportFeedbackBox").html()
        ).render({
          title: "反馈结果",
          data: data
        });
        break;

      // 基因关系申请
      case "relationshipApplyBox":
        var template = Hogan.compile(
          $("#template-relationshipApplyBox").html()
        ).render({
          title: "发送基因关系请求",
          data: data
        });
        break;

      // 视频
      case "video":
        var template = Hogan.compile($("#template-videoBox").html()).render({
          title: "视频"
        });
        break;

      // 单倍群关联
      case "haplogroupApplyBox":
        var template = Hogan.compile(
          $("#template-haplogroupApplyBox").html()
        ).render({
          title: "申请Y染色体关联"
        });
        break;

      // 微解读专业版添加位点
      case "weappAddPositionBox":
        var template = Hogan.compile(
          $("#template-weappAddPositionBox").html()
        ).render({
          title: "批量添加位点"
        });
        break;

      // 家族树邀请
      case "familyInvite":
        var template = Hogan.compile(
          $("#template-familyInviteBox").html()
        ).render({
          title: "邀请",
          type: data.type
        });
        break;

      case "familyInviteEdit":
        var template = Hogan.compile(
          $("#template-familyInviteEditBox").html()
        ).render({
          title: "编辑",
          unique_id: data.unique_id,
          name: data.name,
          job: data.job,
          format: data.format
        });
        break;

      case "familyInviteReportBox":
        var template = Hogan.compile(
          $("#template-familyInviteReportBox").html()
        ).render({
          title: "选择参与对比的数据",
          link_id: data.link_id
        });
        break;

      case "familyInferenceBox":
        var template = Hogan.compile(
          $("#template-familyInviteProjectBox").html()
        ).render({
          title: "选择推算项目",
          tips: "根据已关联家庭成员信息推算其他成员的遗传情况"
        });
        break;

      case "familyInviteProjectBox":
        var template = Hogan.compile(
          $("#template-familyInviteProjectBox").html()
        ).render({
          title: "选择项目进行对比",
          show: "hide"
        });
        break;

      case "allAncestry":
        var template = $("#template-allAncestryBox")
          .html()
          .replace("{{content}}", data.content);
        break;

      // 社区问题申诉
      case "communityAppeal":
        var template = Hogan.compile(
          $("#template-communityappeal").html()
        ).render({});
        break;

      // 基因传兑换
      case "thegene":
        var template = Hogan.compile($("#template-thegeneBox").html()).render(
          {}
        );
        break;

      // 祖源相似性弹窗
      case "ancestrySimilarity":
        var template = Hogan.compile(
          $("#template-ancestrySimilarity").html()
        ).render({
          form_type: data.form_type,
          unique_id: data.unique_id ? data.unique_id : "",
          population: data.population,
          surname: data.surname,
          native_province: data.native_province,
          native_city: data.native_city,
          live_province: data.live_province,
          live_city: data.live_city
        });
        break;

      // 购买页面邀请弹窗
      case "inviteBuyCoupon":
        var template = Hogan.compile(
          $("#template-inviteBuyCoupon").html()
        ).render({
          name: data.name
        });
        break;

      //勋章获取弹窗
      case "medalGetBox":
        var template = Hogan.compile($("#template-medalGetBox").html()).render({
          url: G_STATIC_URL,
          name: data.name,
          medalImg: data.img,
          mdedalInfo: data.mdedalInfo,
          detailUrl: data.detailUrl,
          levelDescription: data.levelDescription
        });
        break;

      // 风险计算器
      case "riskCalBox":
        var template = Hogan.compile($("#template-riskCalBox").html()).render(
          {}
        );
        break;

      case "demoCase":
        var template = Hogan.compile($("#template-democase").html()).render({
          title: data.title,
          count: data.count,
          list: data.list
        });
        break;

      // 动态banner活动
      case "bannerActivityRecruits":
        var template = Hogan.compile(
          $("#template-banneractivityrecruits").html()
        ).render({
          id: data.id,
          type: data.type,
          imgUrl: data.imgUrl,
          title: data.title,
          desc: data.desc,
          link: data.link
        });
        break;
    }

    if (template) {
      if ($("#aw-ajax-box .alert-box").length) {
        $("#aw-ajax-box .alert-box").remove();
      }

      $("#aw-ajax-box")
        .html(template)
        .show();

      switch (type) {
        //打赏列表
        case "crowdsourcingAwardList":
          if (app.totalCount < parseInt(data.count)) {
            $("#noMore").hide();
            $("#loadMore").show();
            $("#loadMore").on("click", function() {
              app.getPayList(++app.page, data.list);
            });
          } else {
            $("#loadMore").hide();
            $("#noMore").show();
          }
          break;
        // 微解读举报
        case "crowdsourcingInform":
          $(".alert-box .btn-submit").click(function() {
            $.post(
              G_BASE_URL + "/crowdsourcing/ajax/report/",
              {
                appname: data.title,
                appid: data.id,
                text: $('.alert-box input[type="radio"]:checked').attr(
                  "data-text"
                )
              },
              function(result) {
                if (result.errno == 1) {
                  AWS.alert("感谢你的反馈!");
                }
              },
              "json"
            );
          });
          break;
        case "crowdsourcingPay":
          var payment_method = "";
          $(".award-box").on("click", function() {
            $("#aw-ajax-box .modal").modal("hide");
            $(".modal-backdrop").detach();
            AWS.loading("show", true);
            if ($(this).index() == 0 || $(this).index() == 1) {
              if ($(this).index() == 0) {
                payment_method = "pingpp_wx";
              } else if ($(this).index() == 1) {
                payment_method = "pingpp_alipay";
              }
              $.post(
                G_BASE_URL + "/crowdsourcing/ajax/buy_by_third_payment/",
                {
                  crowdsourcing_id: app.id,
                  payment_method: payment_method,
                  reward_amount: data.money,
                  payment_act: data.type
                },
                function(res) {
                  AWS.loading("hide", true);
                  res = JSON.parse(res);
                  if (res.errno == -1) {
                    AWS.alert(res.err);
                  } else {
                    location.href = res.rsm.url;
                  }
                }
              );
            } else if ($(this).index() == 2) {
              $.post(
                G_BASE_URL + "/crowdsourcing/ajax/buy_by_wallet/",
                {
                  crowdsourcing_id: app.id,
                  payment_act: data.type,
                  reward_amount: data.money
                },
                function(res) {
                  AWS.loading("hide", true);
                  res = JSON.parse(res);
                  if (res.errno == -1) {
                    AWS.alert(res.err);
                  } else {
                    var msg = data.type == "buy" ? "购买成功" : "打赏成功";
                    AWS.tips("success", msg, function() {
                      location.reload();
                    });
                  }
                }
              );
            } else if ($(this).index() == 3) {
              $.post(
                G_BASE_URL + "/crowdsourcing/ajax/buy_by_integral/",
                {
                  crowdsourcing_id: app.id,
                  payment_act: data.type,
                  reward_amount: data.money
                },
                function(res) {
                  AWS.loading("hide", true);
                  res = JSON.parse(res);
                  if (res.errno == -1) {
                    AWS.alert(res.err);
                  } else {
                    var msg = data.type == "buy" ? "购买成功" : "打赏成功";
                    AWS.tips("success", msg);
                    location.reload();
                  }
                }
              );
            }
          });
          break;
        //打赏
        case "crowdsourcingAward":
          $($(".btn-box a")[0]).addClass("active");
          var rewardAmount = $($(".btn-box a")[0]).attr("data-award");
          $(".btn-box a").click(function() {
            $(this)
              .addClass("active")
              .siblings()
              .removeClass("active");
            rewardAmount = $(this).attr("data-award");
          });
          $(".btn-award").click(function() {
            $("#aw-ajax-box .modal").modal("hide");
            $(".modal-backdrop").detach();
            AWS.dialog("crowdsourcingPay", {
              title: "赞赏",
              money: rewardAmount,
              score: data.rsm.user_integral,
              rate: data.rsm.integral_rate,
              balance: data.rsm.user_wallet_balance,
              type: "reward"
            });
          });
          break;
        case "card":
          $(".card-tips-box ul li").click(function() {
            app.cardId = $(this)
              .find(".card-id")
              .html();
            app.cardName = $(this)
              .find(".card-name")
              .html();
            $(".card-tips-box").modal("hide");
          });
          break;

        case "redirect":
          AWS.Dropdown.bind_dropdown_list(
            $(".aw-question-redirect-box #question-input"),
            "redirect"
          );
          break;

        case "inbox":
          AWS.Dropdown.bind_dropdown_list(
            $(".aw-inbox #invite-input"),
            "inbox"
          );
          //私信用户下拉点击事件
          $(document).on(
            "click",
            ".aw-inbox .aw-dropdown-list li a",
            function() {
              $(".alert-box #quick_publish input.form-control").val(
                $(this).text()
              );
              $(this)
                .parents(".aw-dropdown")
                .hide();
            }
          );
          break;

        case "publish":
          AWS.Dropdown.bind_dropdown_list(
            $(".aw-publish-box #quick_publish_question_content"),
            "publish"
          );
          AWS.Dropdown.bind_dropdown_list(
            $(".aw-publish-box #aw_edit_topic_title"),
            "topic"
          );
          if (parseInt(data.category_enable) == 1) {
            $.get(
              G_BASE_URL + "/publish/ajax/fetch_question_category/",
              function(result) {
                AWS.Dropdown.set_dropdown_list(
                  ".aw-publish-box .dropdown",
                  eval(result),
                  data.category_id
                );

                $(".aw-publish-title .dropdown li a").click(function() {
                  $(".aw-publish-box #quick_publish_category_id").val(
                    $(this).attr("data-value")
                  );
                  $(".aw-publish-box #aw-topic-tags-select").html(
                    $(this).text()
                  );
                });
              }
            );
          } else {
            $(".aw-publish-box .aw-publish-title").hide();
          }

          if (data.ask_user_id != "" && data.ask_user_id != undefined) {
            $(".aw-publish-box .modal-title").html(
              "向 " + data.ask_user_name + " 提问"
            );
          }

          if (
            $("#aw-search-query").val() &&
            $("#aw-search-query").val() !=
              $("#aw-search-query").attr("placeholder")
          ) {
            $("#quick_publish_question_content").val(
              $("#aw-search-query").val()
            );
          }

          AWS.Init.init_topic_edit_box("#quick_publish .aw-edit-topic");

          $("#quick_publish .aw-edit-topic").click();

          $("#quick_publish .close-edit").hide();

          if (data.topic_title) {
            $("#quick_publish .aw-edit-topic")
              .parents(".aw-topic-bar")
              .prepend(
                '<span class="topic-tag"><a class="text">' +
                  data.topic_title +
                  '</a><a class="close" onclick="$(this).parents(\'.topic-tag\').detach();"><i class="icon icon-delete"></i></a><input type="hidden" value="' +
                  data.topic_title +
                  '" name="topics[]" /></span>'
              );
          }

          if (typeof G_QUICK_PUBLISH_HUMAN_VALID != "undefined") {
            $("#quick_publish_captcha").show();
            $("#captcha").click();
          }
          break;

        case "favorite":
          $.get(
            G_BASE_URL + "/favorite/ajax/get_favorite_tags/",
            function(result) {
              var html = "";

              $.each(result, function(i, e) {
                html +=
                  '<li><a data-value="' +
                  e["title"] +
                  '"><span class="title">' +
                  e["title"] +
                  '</span></a><i class="icon icon-followed"></i></li>';
              });

              $(".aw-favorite-tag-list ul").append(html);

              $.post(
                G_BASE_URL + "/favorite/ajax/get_item_tags/",
                {
                  item_id: $('#favorite_form input[name="item_id"]').val(),
                  item_type: $('#favorite_form input[name="item_type"]').val()
                },
                function(result) {
                  if (result != null) {
                    $.each(result, function(i, e) {
                      var index = i;

                      $.each($(".aw-favorite-tag-list ul li .title"), function(
                        i,
                        e
                      ) {
                        if ($(this).text() == result[index]) {
                          $(this)
                            .parents("li")
                            .addClass("active");
                        }
                      });
                    });
                  }
                },
                "json"
              );

              $(document).on(
                "click",
                ".aw-favorite-tag-list ul li a",
                function() {
                  var _this = this,
                    addClassFlag = true,
                    url = G_BASE_URL + "/favorite/ajax/update_favorite_tag/";

                  if (
                    $(this)
                      .parents("li")
                      .hasClass("active")
                  ) {
                    url = G_BASE_URL + "/favorite/ajax/remove_favorite_tag/";

                    addClassFlag = false;
                  }

                  $.post(
                    url,
                    {
                      item_id: $('#favorite_form input[name="item_id"]').val(),
                      item_type: $(
                        '#favorite_form input[name="item_type"]'
                      ).val(),
                      tags: $(_this).attr("data-value")
                    },
                    function(result) {
                      if (result.errno == 1) {
                        if (addClassFlag) {
                          $(_this)
                            .parents("li")
                            .addClass("active");
                        } else {
                          $(_this)
                            .parents("li")
                            .removeClass("active");
                        }
                      }
                    },
                    "json"
                  );
                }
              );
            },
            "json"
          );
          break;

        case "report":
          if (data.report_type == "REPORT") {
            if (data.item_type != "ANCESTRY_STORY_TAG") {
              $(".report-box textarea").hide();

              $(".report-box ul").show();

              $(".report-box input").click(function() {
                $(".report-box textarea").text($(this).attr("value"));
              });
            }
          }
          break;

        case "commentEdit":
          $.get(
            G_BASE_URL + "/question/ajax/fetch_answer_data/" + data.answer_id,
            function(result) {
              $("#editor_reply").html(
                result.answer_content.replace("&amp;", "&")
              );

              var editor = CKEDITOR.replace("editor_reply");

              if (UPLOAD_ENABLE == "Y") {
                var fileupload = new FileUpload(
                  "file",
                  ".edit-comment-box .aw-upload-box .btn",
                  ".edit-comment-box .aw-upload-box .upload-container",
                  G_BASE_URL +
                    "/publish/ajax/attach_upload/id-answer__attach_access_key-" +
                    ATTACH_ACCESS_KEY,
                  {
                    insertTextarea: ".edit-comment-box #editor_reply",
                    editor: editor
                  }
                );

                $.post(
                  G_BASE_URL + "/publish/ajax/answer_attach_edit_list/",
                  "answer_id=" + data.answer_id,
                  function(data) {
                    if (data["err"]) {
                      return false;
                    } else {
                      $.each(data["rsm"]["attachs"], function(i, v) {
                        fileupload.setFileList(v);
                      });
                    }
                  },
                  "json"
                );
              } else {
                $(".edit-comment-box .aw-file-upload-box").hide();
              }
            },
            "json"
          );
          break;

        case "ajaxData":
          $.get(data.url, function(result) {
            $("#aw_dialog_ajax_data").html(result);
          });
          break;

        case "confirm":
          $(".aw-confirm-box .yes").click(function() {
            $(".alert-box").modal("hide");

            $(".modal-backdrop").detach();

            if (callback) {
              callback();
            }

            return false;
          });
          break;

        case "recommend":
          $.get(
            G_BASE_URL + "/help/ajax/list/",
            function(result) {
              if (result && result != 0) {
                var html = "";

                $.each(result, function(i, e) {
                  html +=
                    '<li class="aw-border-radius-5"><img class="aw-border-radius-5" src="' +
                    e.icon +
                    '"><a data-id="' +
                    e.id +
                    '" class="aw-hide-txt">' +
                    e.title +
                    '</a><i class="icon icon-followed"></i></li>';
                });

                $(".aw-recommend-box ul").append(html);

                $.each($(".aw-recommend-box ul li"), function(i, e) {
                  if (
                    data.focus_id ==
                    $(this)
                      .find("a")
                      .attr("data-id")
                  ) {
                    $(this).addClass("active");
                  }
                });

                $(document).on(
                  "click",
                  ".aw-recommend-box ul li a",
                  function() {
                    var _this = $(this),
                      url = G_BASE_URL + "/help/ajax/add_data/",
                      removeClass = false;

                    if (
                      $(this)
                        .parents("li")
                        .hasClass("active")
                    ) {
                      url = G_BASE_URL + "/help/ajax/remove_data/";

                      removeClass = true;
                    }

                    $.post(
                      url,
                      {
                        item_id: data.item_id,
                        id: _this.attr("data-id"),
                        title: _this.text(),
                        type: data.type
                      },
                      function(result) {
                        if (result.errno == 1) {
                          if (removeClass) {
                            _this.parents("li").removeClass("active");
                          } else {
                            $(".aw-recommend-box ul li").removeClass("active");

                            _this.parents("li").addClass("active");
                          }
                        }
                      },
                      "json"
                    );
                  }
                );
              } else {
                $(".error_message").html(_t("请先去后台创建好章节"));

                if ($(".error_message").css("display") != "none") {
                  AWS.shake($(".error_message"));
                } else {
                  $(".error_message").fadeIn();
                }
              }
            },
            "json"
          );
          break;

        // Modify by wegene
        case "genodataReference":
          $(".genodataReference-box .mod-body ul").append(data.content);
          break;

        // Modify by wegene
        case "customerClient":
          $(".customerClient-box .mod-body").append(data.content);
          break;

        // Modify by wegene
        case "resend":
          var app1 = new Vue({
            el: "#resend-dialog",
            data: function() {
              return {
                shippingData: {
                  province: "",
                  city: "",
                  dist: ""
                }
              };
            },
            methods: {
              complete: function(emitData) {
                this.shippingData.province = emitData.province;
                this.shippingData.city = emitData.city;
                this.shippingData.dist = emitData.county;
              }
            }
          });
          break;

        // 微解读
        case "interpretBox":
          $(".interpret-box .form-control").keydown(function(e) {
            if (e.keyCode == 13) {
              $(".interpret-box .icon-search").click();
            }
          });

          $(".interpret-box .icon-search").click(function() {
            $.post(
              G_BASE_URL + "/crowdsourcing/ajax/search_snp_by_rsid/",
              {
                rsid: $(this)
                  .parents(".search-box")
                  .find(".form-control")
                  .val()
              },
              function(result) {
                if (result.errno == -1) {
                  $(".interpret-box .err")
                    .html(result.err)
                    .show();

                  $(
                    ".interpret-box .search-list .title, .interpret-box .search-list ul"
                  ).hide();

                  $(".interpret-box .btn").addClass("btn-disabled");
                } else if (result.errno == 1) {
                  if (result.rsm.crowdsourcing instanceof Array) {
                    $(".interpret-box .search-list ul").html("");

                    $(".interpret-box .err").hide();

                    $(".interpret-box .search-list .title").html(
                      "该位点暂无项目"
                    );

                    $(
                      ".interpret-box .search-list .title, .interpret-box .search-list ul"
                    ).show();
                  } else {
                    $(".interpret-box .search-list ul").html("");

                    for (var i in result.rsm.crowdsourcing) {
                      $(".interpret-box .search-list ul").append(
                        '<li><a  href="' +
                          G_BASE_URL +
                          "/crowdsourcing/details/" +
                          i +
                          '">' +
                          result.rsm.crowdsourcing[i] +
                          "</a></li>"
                      );
                    }

                    $(".interpret-box .err").hide();

                    $(".interpret-box .search-list .title").html(
                      "该位点已有项目"
                    );

                    $(
                      ".interpret-box .search-list .title, .interpret-box .search-list ul"
                    ).show();
                  }

                  $(".interpret-box .btn")
                    .attr(
                      "href",
                      G_BASE_URL +
                        "/crowdsourcing/create/" +
                        $(".interpret-box .form-control").val()
                    )
                    .removeClass("btn-disabled");
                }
              },
              "json"
            );
          });
          break;

        // 微解读授权
        case "interpretAuthorityBox":
          $(".interpret-authority-box .btn-submit").click(function() {
            $(".alert-box").modal("hide");
            AWS.loading("show", true);

            // TODO: 待未来进行封装
            $.ajaxSetup({
              crossDomain: true,
              xhrFields: {
                withCredentials: true
              }
            });

            $.post(
              G_BASE_URL_NON_CDN + "/crowdsourcing/ajax/authorize/",
              {
                crowdsourcing_id: app.id ? app.id : ""
              },
              function(result) {
                AWS.loading("hide", true);
                if (result.errno == -1 && !result.rsm) {
                  AWS.dialog("tips", {
                    title: "无法查看",
                    message: '<p class="text-center">' + result.err + "</p>"
                  });
                } else if (
                  result.errno == -1 &&
                  result.rsm.error_type == "apply_error"
                ) {
                  AWS.dialog("tips", {
                    title: "无法查看",
                    message: '<p class="text-center">' + result.err + "</p>"
                  });
                } else if (
                  result.errno == -1 &&
                  result.rsm.error_type == "rsid_error"
                ) {
                  AWS.dialog("tips", {
                    title: "无法查看",
                    message:
                      "<p>位点未检出或不在您的报告格式上。未检出的基因位点通常有两种情况:</p><p>1. 不同公司的芯片设计了不同的基因位点，该位点不在检测所使用的芯片上;</p><p>2. 该位点在检测芯片上， 但未能通过数据质控程序</p>"
                  });
                } else if (result.errno == 1) {
                  window.location.reload();
                }
              },
              "json"
            );
          });
          break;

        case "interpretAuthorityProBox":
          $(".interpret-authority-box .btn-submit").click(function() {
            $(".alert-box").modal("hide");

            AWS.loading("show", true);

            // TODO: 待未来进行封装
            $.ajaxSetup({
              crossDomain: true,
              xhrFields: {
                withCredentials: true
              }
            });

            $.post(
              G_BASE_URL_NON_CDN + "/weapp/ajax/authorize/",
              {
                weapp_id: app.weappId || ""
              },
              function(result) {
                AWS.loading("hide", true);
                if (result.errno == -1 && !result.rsm) {
                  AWS.dialog("tips", {
                    title: "无法查看",
                    message: '<p class="text-center">' + result.err + "</p>"
                  });
                } else if (
                  result.errno == -1 &&
                  result.rsm.error_type == "apply_error"
                ) {
                  AWS.dialog("tips", {
                    title: "无法查看",
                    message: '<p class="text-center">' + result.err + "</p>"
                  });
                } else if (
                  result.errno == -1 &&
                  result.rsm.error_type == "rsid_error"
                ) {
                  AWS.dialog("tips", {
                    title: "无法查看",
                    message:
                      "<p>位点未检出或不在您的报告格式上。未检出的基因位点通常有两种情况:</p><p>1. 不同公司的芯片设计了不同的基因位点，该位点不在检测所使用的芯片上;</p><p>2. 该位点在检测芯片上， 但未能通过数据质控程序</p>"
                  });
                } else if (result.errno == 1) {
                  window.location.reload();
                }
              },
              "json"
            );
          });
          break;

        // 微解读专业版添加位点
        case "weappAddPositionBox":
          $(".weapp-add-position-box .btn-publish").click(function() {
            var template_arr = [],
              data = $(".weapp-add-position-box textarea").val();

            data = data.split("\n");

            for (var i = 0; i < data.length; i++) {
              var template =
                '<label><input class="form-control form-mini" name="assign_position[]" type="text" value="' +
                data[i] +
                '"> <a><i class="icon icon-delete"></i></a></label>';

              template_arr.push(template);
            }

            $(".position dd").prepend(template_arr.join(""));

            $(".alert-box").modal("hide");
          });
          break;

        // 报告结果错误反馈
        case "reportFeedbackBox":
          if ($(".error-result-feedback .list").text().length) {
            var arr = $(".error-result-feedback .list")
                .text()
                .trim()
                .split("\\n"),
              template = ['<option value=""></option>'];

            for (i = 0; i < arr.length; i++) {
              template.push(
                '<option value="' + arr[i] + '">' + arr[i] + "</optoin>"
              );
            }

            $(".report-feedback-box .reason").html(template.join(""));
          }

          $(".report-feedback-box .btn-submit").click(function() {
            AWS.ajax_post($("#report_feedback_form"), function(type, result) {
              if (result.errno == -1) {
                alert(result.err);

                $(".alert-box").modal("hide");
              }
            });
          });
          break;

        // 家族树邀请
        case "familyInvite":
          switch (data.type) {
            case "brothersister":
            case "friends":
              $(".family-invite-box .base-info").show();
              $(".family-invite-box ." + data.type).show();
              $(
                '.family-invite-box .relation:not(".' + data.type + '")'
              ).detach();
              break;

            default:
              $(".family-invite-box .base-info").detach();
              break;
          }

          // 报告列表
          if ($(".aw-user-nav .aw-dropdown-list .report").length) {
            $.each($(".aw-user-nav .aw-dropdown-list .report"), function(i, e) {
              $(".family-invite-box .report-list").prepend(
                '<li><label><input type="radio" name="connect_unique_id" value="' +
                  $(this).attr("data-id") +
                  '" /> ' +
                  $(this)
                    .find("a")
                    .html() +
                  "</label></li>"
              );
            });
          }

          AWS.Dropdown.bind_dropdown_list(
            $(".family-invite-box .connect-user-input"),
            "inbox"
          );

          //私信用户下拉点击事件
          $(document).on(
            "click",
            ".family-invite-box .aw-dropdown-list li a",
            function() {
              $(".family-invite-box .connect-user-input").val($(this).text());
              $(this)
                .parents(".aw-dropdown")
                .hide();
            }
          );

          $(".family-invite-box .btn-submit").click(function() {
            if ($(".connect-user-radio").is(":checked")) {
              if ($(".connect-user-input").val().length == 0) {
                $(".error_message em").html("请输入对方用户名!");

                if ($(".error_message").css("display") != "none") {
                  AWS.shake($(".error_message"));
                } else {
                  $(".error_message").fadeIn();
                }
              } else {
                AWS.ajax_post(
                  $("#send_link_request"),
                  AWS.ajax_processer,
                  "error_message"
                );
              }
            } else {
              AWS.ajax_post(
                $("#send_link_request"),
                AWS.ajax_processer,
                "error_message"
              );
            }
          });

          // 邀请选择wegene用户
          $(".family-invite-box .connect-user-input").focus(function() {
            $(".family-invite-box .connect-user-radio").click();
          });
          break;

        // 家族树编辑资料
        case "familyInviteEdit":
          // 更多信息展开
          $(".toggle-info").click(function() {
            var icon = $(this).find(".icon");

            if (icon.hasClass("icon-down")) {
              icon.removeClass("icon-down").addClass("icon-up");
              $(".more-info").slideDown();
            } else {
              icon.removeClass("icon-up").addClass("icon-down");
              $(".more-info").slideUp();
            }
          });

          // 性别
          if (data.sex == 1) {
            $(".family-invite-box .male").attr("checked", true);
          } else {
            $(".family-invite-box .female").attr("checked", true);
          }

          // 生日下拉菜单
          var birthday = data.birthday.split("-");
          $.calender({
            year_el: $(".family-invite-box .birthday-y"),
            month_el: $(".family-invite-box .birthday-m"),
            day_el: $(".family-invite-box .birthday-d"),
            year: birthday[0],
            month: birthday[1],
            day: birthday[2]
          });

          // 籍贯下拉
          $(".family-invite-box .native_province").citySelect({
            prov: data.native_province,
            city: data.native_city
            // dist:"<?php echo $this->user_info['dist']; ?>"
          });

          // 现居下拉
          $(".family-invite-box .live_province").citySelect({
            prov: data.province,
            city: data.city
            // dist:"<?php echo $this->user_info['dist']; ?>"
          });
          break;

        // 家族树邀请选择报告
        case "familyInviteReportBox":
          // 报告列表
          if ($(".aw-user-nav .aw-dropdown-list .report").length) {
            $.each($(".aw-user-nav .aw-dropdown-list .report"), function(i, e) {
              $(".family-invite-report-box .report-list").prepend(
                '<li><label><input type="radio" name="connect_unique_id" value="' +
                  $(this).attr("data-id") +
                  '" />' +
                  $(this)
                    .find("a")
                    .html() +
                  "</label></li>"
              );
            });
          }

          $(".family-invite-report-box input").click(function() {
            var unique_id = $(".family-invite-report-box input:checked").val();

            $.post(
              G_BASE_URL + "/family/ajax/accept_link_request/",
              {
                link_id: data.link_id,
                connect_unique_id: unique_id
              },
              function(result) {
                if (result.errno == -1) {
                  $(".error_message em").html(result.err);

                  if ($(".error_message").css("display") != "none") {
                    AWS.shake($(".error_message"));
                  } else {
                    $(".error_message").fadeIn();
                  }
                } else {
                  window.location.reload();
                }
              },
              "json"
            );
          });
          break;

        // 家族树项目选择
        case "familyInviteProjectBox":
          if (CASE_LIST) {
            var template_arr = [];

            // 细分版块对应信息
            var config_nation = {
              // start 中华民族
              han_southern: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "han_southern",
                name: "南方汉族",
                icon: "a-han_southern",
                positionLeft: "443",
                positionTop: "357",
                fontSize: "166",
                width: "209",
                height: "166"
              },
              han_northern: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "han_northern",
                name: "北方汉族",
                icon: "a-han_northern",
                positionLeft: "497",
                positionTop: "208",
                fontSize: "214",
                width: "246",
                height: "214"
              },
              dai: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "dai",
                name: "傣族",
                icon: "a-dai",
                positionLeft: "312",
                positionTop: "396",
                fontSize: "31",
                width: "43",
                height: "31"
              },
              tungus: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "tungus",
                name: "通古斯族群",
                icon: "a-tungus",
                positionLeft: "576",
                positionTop: "134",
                fontSize: "155",
                width: "127",
                height: "155",
                tips: "包括锡伯族、鄂伦春族和赫哲族等"
              },
              lahu: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "lahu",
                name: "拉祜族",
                icon: "a-lahu",
                positionLeft: "298",
                positionTop: "414",
                fontSize: "31",
                width: "39",
                height: "31"
              },
              she: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "she",
                name: "畲族",
                icon: "a-she",
                positionLeft: "531",
                positionTop: "343",
                fontSize: "60",
                width: "41",
                height: "60"
              },
              miao_yao: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "miao_yao",
                name: "苗瑶语族群",
                icon: "a-miao_yao",
                positionLeft: "375",
                positionTop: "359",
                fontSize: "74",
                width: "66",
                height: "74"
              },
              mongolian: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "mongolian",
                name: "蒙古语族群",
                icon: "a-mongola",
                positionLeft: "395",
                positionTop: "150",
                fontSize: "191",
                width: "353",
                height: "191",
                tips: "包括蒙古族、达斡尔族和土族等"
              },
              uygur: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "uygur",
                name: "维吾尔族",
                icon: "a-uygur",
                positionLeft: "178",
                positionTop: "152",
                fontSize: "157",
                width: "249",
                height: "157"
              },
              tibetan: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "tibetan",
                name: "藏族",
                icon: "a-tibetan",
                positionLeft: "235",
                positionTop: "274",
                fontSize: "178",
                width: "263",
                height: "178"
              },
              gaoshan: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "gaoshan",
                name: "高山族群",
                icon: "a-gaoshan",
                positionLeft: "551",
                positionTop: "397",
                fontSize: "56",
                width: "24",
                height: "56",
                tips: "包括阿美族和泰雅族等"
              },
              ny: {
                parent_block: "chinese_nation",
                parent_block_name: "中华民族",
                key: "ny",
                name: "纳西/彝族",
                icon: "a-ny",
                positionLeft: "314",
                positionTop: "352",
                fontSize: "107",
                width: "62",
                height: "107",
                tips: "包括彝族和纳西族等"
              },
              // end 中华民族
              // start 东北亚
              korean: {
                parent_block: "ne_asian",
                parent_block_name: "东北亚",
                key: "korean",
                name: "韩国人",
                icon: "korean"
              },
              japanese: {
                parent_block: "ne_asian",
                parent_block_name: "东北亚",
                key: "japanese",
                name: "日本人",
                icon: "japanese"
              },
              yakut: {
                parent_block: "ne_asian",
                parent_block_name: "东北亚",
                key: "yakut",
                name: "雅库特人",
                icon: "yakut"
              },
              // end 东北亚
              // start 东南亚
              thai: {
                parent_block: "se_asian",
                parent_block_name: "东南亚",
                key: "thai",
                name: "泰国人",
                icon: "thai"
              },
              cambodian: {
                parent_block: "se_asian",
                parent_block_name: "东南亚",
                key: "cambodian",
                name: "柬埔寨人",
                icon: "cambodian"
              },
              kinh: {
                parent_block: "se_asian",
                parent_block_name: "东南亚",
                key: "kinh",
                name: "越南京族",
                icon: "kinh"
              },
              // end 东南亚
              // start 南亚
              mala: {
                parent_block: "south_asian",
                parent_block_name: "南亚",
                key: "mala",
                name: "印度人",
                icon: "mala"
              },
              bengali: {
                parent_block: "south_asian",
                parent_block_name: "南亚",
                key: "bengali",
                name: "孟加拉人",
                icon: "bengali"
              },
              sindhi: {
                parent_block: "south_asian",
                parent_block_name: "南亚",
                key: "sindhi",
                name: "信德人",
                icon: "sindhi"
              },
              // end 南亚
              // start 中亚
              kyrgyz: {
                parent_block: "central_asian",
                parent_block_name: "中亚",
                key: "kyrgyz",
                name: "柯尔克孜族",
                icon: "a-kyrgyz",
                positionLeft: "79",
                positionTop: "165",
                fontSize: "70",
                width: "61",
                height: "70"
              },
              uzbek: {
                parent_block: "central_asian",
                parent_block_name: "中亚",
                key: "uzbek",
                name: "乌孜别克族",
                icon: "a-uzbek",
                positionLeft: "115",
                positionTop: "98",
                fontSize: "197",
                width: "230",
                height: "197"
              },
              // end 中亚
              // start 中东
              iranian: {
                parent_block: "middle_eastern",
                parent_block_name: "中东",
                key: "iranian",
                name: "伊朗人",
                icon: "iranian"
              },
              saudi: {
                parent_block: "middle_eastern",
                parent_block_name: "中东",
                key: "saudi",
                name: "沙特阿拉伯人",
                icon: "saudi"
              },
              egyptian: {
                parent_block: "middle_eastern",
                parent_block_name: "中东",
                key: "egyptian",
                name: "埃及人",
                icon: "egyptian"
              },
              // end 中东
              // start 非洲
              mbuti: {
                parent_block: "african",
                parent_block_name: "非洲",
                key: "mbuti",
                name: "姆布蒂人",
                icon: "mbuti"
              },
              yoruba: {
                parent_block: "african",
                parent_block_name: "非洲",
                key: "yoruba",
                name: "约鲁巴人",
                icon: "yoruba"
              },
              somali: {
                parent_block: "african",
                parent_block_name: "非洲",
                key: "somali",
                name: "索马里人",
                icon: "somali"
              },
              bantusa: {
                parent_block: "african",
                parent_block_name: "非洲",
                key: "bantusa",
                name: "南非班图人",
                icon: "bantusa"
              },
              // end 非洲
              // start 欧洲
              french: {
                parent_block: "european",
                parent_block_name: "欧洲",
                key: "french",
                name: "法国人",
                icon: "french"
              },
              sardinian: {
                parent_block: "european",
                parent_block_name: "欧洲",
                key: "sardinian",
                name: "意大利撒丁岛人",
                icon: "sardinian"
              },
              finnish_russian: {
                parent_block: "european",
                parent_block_name: "欧洲",
                key: "finnish_russian",
                name: "芬兰/俄罗斯人",
                icon: "finnish_russian"
              },
              hungarian: {
                parent_block: "european",
                parent_block_name: "欧洲",
                key: "hungarian",
                name: "匈牙利人",
                icon: "hungarian"
              },
              balkan: {
                parent_block: "european",
                parent_block_name: "欧洲",
                key: "balkan",
                name: "巴尔干半岛",
                icon: "balkan"
              },
              spanish: {
                parent_block: "european",
                parent_block_name: "欧洲",
                key: "spanish",
                name: "西班牙人",
                icon: "spanish"
              },
              ashkenazi: {
                parent_block: "european",
                parent_block_name: "欧洲",
                key: "ashkenazi",
                name: "德系犹太人",
                icon: "ashkenazi"
              },
              english: {
                parent_block: "european",
                parent_block_name: "欧洲",
                key: "english",
                name: "英国人",
                icon: "english"
              },
              // end 欧洲
              // 美洲
              eskimo: {
                parent_block: "american",
                parent_block_name: "美洲",
                key: "eskimo",
                name: "因纽特人",
                icon: "eskimo"
              },
              pima: {
                parent_block: "american",
                parent_block_name: "美洲",
                key: "pima",
                name: "美洲土著",
                icon: "pima"
              },
              mayan: {
                parent_block: "american",
                parent_block_name: "美洲",
                key: "mayan",
                name: "墨西哥玛雅人",
                icon: "mayan"
              },
              // end 美洲
              // start 大洋洲
              papuan: {
                parent_block: "oceanian",
                parent_block_name: "大洋洲",
                key: "papuan",
                name: "巴布亚人",
                icon: "papuan"
              }
              // end 大洋洲
            };

            var ancestry_template =
              '<dl><dt>祖源分析<i class="icon icon-down"></i></dt><dd><ul>';

            ancestry_template +=
              '<li><a data-type="祖源分析" data-id="y">父系单倍群</a></li><li><a data-type="祖源分析" data-id="mt">母系单倍群</a></li><li><a data-type="祖源分析" data-id="ancient_ancestry_neandertal">尼安德特人成分</a></li>';

            for (var i in config_nation) {
              ancestry_template +=
                '<li><a data-type="祖源分析" data-id="' +
                i +
                '">' +
                config_nation[i].name +
                "成分</a></li>";
            }

            ancestry_template += "</ul></dd></dl>";

            template_arr.push(ancestry_template);

            for (var i in CASE_LIST) {
              var template =
                "<dl><dt>" + i + '<i class="icon icon-down"></i></dt><dd><ul>';

              for (var j in CASE_LIST[i]) {
                template +=
                  '<li><a data-type="' +
                  i +
                  '" data-id="' +
                  j +
                  '">' +
                  CASE_LIST[i][j] +
                  "</a></li>";
              }

              template += "</ul></dd></dl>";

              template_arr.push(template);
            }

            $(".family-invite-project-box .report-list").html(
              template_arr.join("")
            );

            // 列表展开
            $(".family-invite-project-box .report-list dt").click(function() {
              var icon = $(this).find(".icon"),
                list = $(this)
                  .parents("dl")
                  .find("ul");

              if (list.is(":visible")) {
                icon.addClass("icon-down").removeClass("icon-up");
                list.slideUp("");
              } else {
                $(".family-invite-project-box .report-list ul").slideUp();
                $(".family-invite-project-box .report-list .icon")
                  .removeClass("icon-up")
                  .addClass("icon-down");
                icon.addClass("icon-up").removeClass("icon-down");
                list.slideDown("");
              }
            });

            // 列表点击
            $(".family-invite-project-box .report-list li a").click(function() {
              var caseid = $(this).attr("data-id"),
                title = $(this).text(),
                type = $(this).attr("data-type");

              window.location.href =
                G_BASE_URL +
                "/dna_family/compare/?caseId=" +
                caseid +
                "&category=" +
                type +
                "&caseName=" +
                title;
            });
          }
          break;

        // 家族树推算
        case "familyInferenceBox":
          if (INFERENCE_CASE_LIST) {
            var template_arr = [];

            for (var i in INFERENCE_CASE_LIST) {
              var template =
                "<dl><dt>" + i + '<i class="icon icon-down"></i></dt><dd><ul>';

              for (var j in INFERENCE_CASE_LIST[i]) {
                template +=
                  '<li><a href="' +
                  G_BASE_URL +
                  "/family/inference/?caseId=" +
                  j +
                  "&category=" +
                  i +
                  "&caseName=" +
                  INFERENCE_CASE_LIST[i][j] +
                  '">' +
                  INFERENCE_CASE_LIST[i][j] +
                  "</a></li>";
              }

              template += "</ul></dd></dl>";

              template_arr.push(template);
            }

            $(".family-invite-project-box .report-list").html(
              template_arr.join("")
            );

            // 列表展开
            $(".family-invite-project-box .report-list dt").click(function() {
              var icon = $(this).find(".icon"),
                list = $(this)
                  .parents("dl")
                  .find("ul");

              if (list.is(":visible")) {
                icon.addClass("icon-down").removeClass("icon-up");
                list.slideUp("");
              } else {
                $(".family-invite-project-box .report-list ul").slideUp();
                $(".family-invite-project-box .report-list .icon")
                  .removeClass("icon-up")
                  .addClass("icon-down");
                icon.addClass("icon-up").removeClass("icon-down");
                list.slideDown("");
              }
            });
          }
          break;

        // 基因传兑换
        case "thegene":
          $(".the-gene-box .province").citySelect({
            prov: "",
            city: "",
            dist: "",
            url: G_STATIC_URL + "/js/city_buy.min.js"
          });

          $(".the-gene-box .btn").click(function() {
            var _this = $(this);

            $(this).addClass("disabled");

            AWS.loading("show");

            $.post(
              G_BASE_URL + "/events/ajax/the_gene/add_exchange_order/",
              {
                email: $(".the-gene-box .email").val(),
                shipping_name: $(".the-gene-box .shipping_name").val(),
                shipping_mobile: $(".the-gene-box .shipping_mobile").val(),
                province: $(".the-gene-box .prov").val(),
                city: $(".the-gene-box .city").val(),
                dist: $(".the-gene-box .dist").val(),
                shipping_address: $(".the-gene-box .shipping_address").val()
              },
              function(result) {
                _this.removeClass("disabled");

                AWS.loading("hide");

                if (result.errno == 1) {
                  AWS.alert("兑换成功");
                  $("#user_integral").html(
                    parseInt($("#user_integral").html()) - 2000
                  );
                } else if (result.errno == -1) {
                  if (!$(".error_message").length) {
                    alert(result.err);
                  } else if ($(".error_message em").length) {
                    $(".error_message em").html(result.err);
                  } else {
                    $(".error_message").html(result.err);
                  }

                  if ($(".error_message").css("display") != "none") {
                    AWS.shake($(".error_message"));
                  } else {
                    $(".error_message").fadeIn();
                  }
                }
              },
              "json"
            );
          });
          break;

        case "inviteBuyCoupon":
          AWS.countdown(1532447999, $(".invite-buy-coupon .count-down"));

          AWS.G.countdownTimer = setInterval(function() {
            AWS.countdown(1532447999, $(".invite-buy-coupon .count-down"));
          }, 1000);
          break;

        // 祖源相似性弹窗
        case "ancestrySimilarity":
          // 籍贯下拉
          $(".ancestry-similarity-box .native_province").citySelect({
            prov: data.native_province,
            city: data.native_city,
            url: G_STATIC_URL + "/js/city_surname.min.js"
            // dist:"<?php echo $this->user_info['dist']; ?>"
          });

          // 现居下拉
          $(".ancestry-similarity-box .live_province").citySelect({
            prov: data.live_province,
            city: data.live_city,
            url: G_STATIC_URL + "/js/city_surname.min.js"
            // dist:"<?php echo $this->user_info['dist']; ?>"
          });

          $(".ancestry-similarity-box .population").val(data.population);
          break;

        // 风险计算器
        case "riskCalBox":
          var survey_data = eval("(" + data.survey_data + ")");

          var options = {
            locale: "zh-cn",
            completedHtml: " ",
            requiredText: "",
            clearInvisibleValues: true,
            showTitle: false,
            showPageTitles: false,
            showQuestionNumbers: "off",
            showProgressBar: "off",
            completeText: "提交计算",
            completedHtml:
              '<div class="text-center color-999">正在计算，请稍后...</div>'
          };

          // survey_data = $.extend(survey_data, options);
          options.pages = survey_data.pages;
          Survey.Survey.cssType = "bootstrap";
          Survey.defaultBootstrapCss.navigationButton = "btn";

          window.survey = new Survey.Model(options);

          var myCss = {
            body: "padding-0",
            footer: "text-center margin-top-20",
            progress: "progress center-block",
            row: "item",
            question: {
              mainRoot: "question",
              title: "title"
            },
            navigation: {
              complete: "margin-0 submit btn-primary",
              next: "next margin-0  btn-primary",
              prev: "prev pull-left btn-gray"
            },
            matrixdynamic: {
              root: "table",
              button: "matrixdynamic-btn"
            }
          };

          $("#riskSurveyElement").Survey({
            model: survey,
            css: myCss,
            onComplete: function() {
              $.post(
                G_BASE_URL + "/survey2/ajax/submit/",
                {
                  answer_json: JSON.stringify(survey.data),
                  survey_id: data.survey_id,
                  user_data_id: data.unique_id,
                  user_tag: data.user_tag
                },
                function(result) {
                  if (result.errno == 1) {
                    var url = G_BASE_URL + "/report2/ajax/calculate_risk/";

                    $.post(
                      url,
                      {
                        caseid: data.case_id,
                        widget_id: data.widget_id,
                        environment: data.environment
                      },
                      function(result) {
                        if (result.errno == 1) {
                          window.location.reload();
                        }
                      }
                    );
                  }
                },
                "json"
              );
            }
          });

          break;

        // 测序数据下载
        case "dataDownloadRaw":
          $(".alert-box .btn-submit").click(function() {
            AWS.ajax_post($("#download_form"), function(type, result) {
              if (result.errno == -1) {
                if (!$(".error_message").length) {
                  alert(result.err);
                } else if ($(".error_message em").length) {
                  $(".error_message em").html(result.err);
                } else {
                  $(".error_message").html(result.err);
                }

                if ($(".error_message").css("display") != "none") {
                  AWS.shake($(".error_message"));
                } else {
                  $(".error_message").fadeIn();
                }
              } else if (result.errno == 1) {
                AWS.alert(result.err);
              }
            });
          });
          break;

        case "bannerActivityRecruits":
          $(".banner-activity-recruits .btn-hollow").click(function() {
            var dataId = $(this).attr("data-id");
            window.localStorage.setItem(
              "recruits" + dataId,
              Math.floor(new Date().getTime() / 1000) + 86400
            );
            $("#aw-ajax-box .modal").modal("hide");
          });

          $(".banner-activity-recruits .set-close").click(function() {
            $.post(
              G_BASE_URL + "/account/ajax/set_recruit_close_time_by_id/",
              {
                id: $(this).attr("data-id")
              },
              function(result) {
                if (result.errno == 1) {
                  $("#aw-ajax-box .modal").modal("hide");
                }
              },
              "json"
            );
          });
          break;
      }

      $("#aw-ajax-box .modal").modal("show");

      $(".customerClient-box .modal-body").scroll(function() {
        if (
          parseInt($(".customerClient-box .modal-body").scrollTop()) + 300 >=
          parseInt($(".customerClient-box .mod-body").innerHeight())
        ) {
          $(".customerClient-box .btn-primary").removeClass("disabled");
        }
      });
    }
  },

  // 兼容placeholder
  check_placeholder: function(selector) {
    $.each(selector, function() {
      if (typeof $(this).attr("placeholder") != "undefined") {
        $(this).attr("data-placeholder", "true");

        if ($(this).val() == "") {
          $(this)
            .addClass("aw-placeholder")
            .val($(this).attr("placeholder"));
        }

        $(this).focus(function() {
          if ($(this).val() == $(this).attr("placeholder")) {
            $(this)
              .removeClass("aw-placeholder")
              .val("");
          }
        });

        $(this).blur(function() {
          if ($(this).val() == "") {
            $(this)
              .addClass("aw-placeholder")
              .val($(this).attr("placeholder"));
          }
        });
      }
    });
  },

  // 回复背景高亮
  hightlight: function(selector, class_name) {
    if (selector.hasClass(class_name)) {
      return true;
    }

    var hightlight_timer_front = setInterval(function() {
      selector.addClass(class_name);
    }, 500);

    var hightlight_timer_background = setInterval(function() {
      selector.removeClass(class_name);
    }, 600);

    setTimeout(function() {
      clearInterval(hightlight_timer_front);
      clearInterval(hightlight_timer_background);

      selector.addClass(class_name);
    }, 1200);

    setTimeout(function() {
      selector.removeClass(class_name);
    }, 6000);
  },

  nl2br: function(str) {
    return str.replace(new RegExp("\r\n|\n\r|\r|\n", "g"), "<br />");
  },

  content_switcher: function(hide_el, show_el) {
    hide_el.hide();
    show_el.fadeIn();
  },

  htmlspecialchars: function(text) {
    return text
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;");
  },

  get_nation_options: function() {
    var nation = {
      data: [
        { id: "01", name: "汉族" },
        { id: "02", name: "蒙古族" },
        { id: "03", name: "回族" },
        { id: "04", name: "藏族" },
        { id: "05", name: "维吾尔族" },
        { id: "06", name: "苗族" },
        { id: "07", name: "彝族" },
        { id: "08", name: "壮族" },
        { id: "09", name: "布依族" },
        { id: "10", name: "朝鲜族" },
        { id: "11", name: "满族" },
        { id: "12", name: "侗族" },
        { id: "13", name: "瑶族" },
        { id: "14", name: "白族" },
        { id: "15", name: "土家族" },
        { id: "16", name: "哈尼族" },
        { id: "17", name: "哈萨克族" },
        { id: "18", name: "傣族" },
        { id: "19", name: "黎族" },
        { id: "20", name: "傈僳族" },
        { id: "21", name: "佤族" },
        { id: "22", name: "畲族" },
        { id: "23", name: "高山族" },
        { id: "24", name: "拉祜族" },
        { id: "25", name: "水族" },
        { id: "26", name: "东乡族" },
        { id: "27", name: "纳西族" },
        { id: "28", name: "景颇族" },
        { id: "29", name: "柯尔克孜族" },
        { id: "30", name: "土族" },
        { id: "31", name: "达斡尔族" },
        { id: "32", name: "仫佬族" },
        { id: "33", name: "羌族" },
        { id: "34", name: "布朗族" },
        { id: "35", name: "撒拉族" },
        { id: "36", name: "毛难族" },
        { id: "37", name: "仡佬族" },
        { id: "38", name: "锡伯族" },
        { id: "39", name: "阿昌族" },
        { id: "40", name: "普米族" },
        { id: "41", name: "塔吉克族" },
        { id: "42", name: "怒族" },
        { id: "43", name: "乌孜别克族" },
        { id: "44", name: "俄罗斯族" },
        { id: "45", name: "鄂温克族" },
        { id: "46", name: "崩龙族" },
        { id: "47", name: "保安族" },
        { id: "48", name: "裕固族" },
        { id: "49", name: "京族" },
        { id: "50", name: "塔塔尔族" },
        { id: "51", name: "独龙族" },
        { id: "52", name: "鄂伦春族" },
        { id: "53", name: "赫哲族" },
        { id: "54", name: "门巴族" },
        { id: "55", name: "珞巴族" },
        { id: "56", name: "基诺族" }
      ]
    };

    var nation_template = [];

    for (var i = 0; i < nation.data.length; i++) {
      nation_template.push(
        '<option value="' +
          nation.data[i].name +
          '">' +
          nation.data[i].name +
          "</option>"
      );
    }

    return nation_template.join("");
  },

  birthday_select: function(el_y, el_m, el_d) {
    var start_year = 1900,
      date = new Date(),
      year = date.getFullYear(),
      year_template = [],
      month_template = [];

    while (start_year < year) {
      year_template.push(
        '<option value="' + start_year + '">' + start_year + "</option>"
      );
      start_year++;
    }

    el_y.html(year_template.join(""));

    for (var i = 1; i <= 12; i++) {
      month_template.push('<option value="' + i + '">' + i + "</option>");
    }

    el_m.html(month_template.join(""));

    el_d.html(_cal_day(1));

    el_m.change(function() {
      el_d.html(_cal_day($(this).val()));
    });

    function _cal_day(month) {
      var day_template = [],
        max = 31;

      switch (month) {
        case "2":
          max = 28;
          break;

        case "4":
        case "6":
        case "9":
        case "11":
          max = 30;
          break;

        default:
          max = 31;
          break;
      }

      for (var i = 1; i <= max; i++) {
        day_template.push('<option value="' + i + '">' + i + "</option>");
      }

      return day_template.join("");
    }
  },

  /*
   * 用户头像提示box效果
   *  @params
   *  type : user/topic
   *	nTop    : 焦点到浏览器上边距
   *	nRight  : 焦点到浏览器右边距
   *	nBottom : 焦点到浏览器下边距
   *	left    : 焦点距离文档左偏移量
   *	top     : 焦点距离文档上偏移量
   **
   */
  show_card_box: function(
    selector,
    type,
    time //selector -> .aw-user-name/.topic-tag
  ) {
    if (!time) {
      var time = 300;
    }

    $(document).on("mouseover", selector, function() {
      clearTimeout(AWS.G.card_box_hide_timer);
      var _this = $(this);
      AWS.G.card_box_show_timer = setTimeout(function() {
        //判断用户id or 话题id 是否存在
        if (_this.attr("data-id")) {
          switch (type) {
            case "user":
              //检查是否有缓存
              if (AWS.G.cashUserData.length == 0) {
                _getdata("user", "/people/ajax/user_info/uid-");
              } else {
                var flag = 0;
                //遍历缓存中是否含有此id的数据
                _checkcash("user");
                if (flag == 0) {
                  _getdata("user", "/people/ajax/user_info/uid-");
                }
              }
              break;

            case "topic":
              //检查是否有缓存
              if (AWS.G.cashTopicData.length == 0) {
                _getdata("topic", "/topic/ajax/topic_info/topic_id-");
              } else {
                var flag = 0;
                //遍历缓存中是否含有此id的数据
                _checkcash("topic");
                if (flag == 0) {
                  _getdata("topic", "/topic/ajax/topic_info/topic_id-");
                }
              }
              break;
          }
        }

        //获取数据
        function _getdata(type, url) {
          if (type == "user") {
            $.get(
              G_BASE_URL + url + _this.attr("data-id"),
              function(result) {
                var focus = result.focus,
                  verified = result.verified,
                  focusTxt;

                if (focus == 1) {
                  focus = "active";
                  focusTxt = "取消关注";
                } else {
                  focus = "";
                  focusTxt = "关注";
                }

                if (result.verified == "enterprise") {
                  verified_enterprise = "icon-v i-ve";
                  verified_title = "企业认证";
                } else if (result.verified == "personal") {
                  verified_enterprise = "icon-v";
                  verified_title = "个人认证";
                } else {
                  verified_enterprise = verified_title = "";
                }

                //动态插入盒子
                $("#aw-ajax-box").html(
                  Hogan.compile(AW_TEMPLATE.userCard).render({
                    verified_enterprise: verified_enterprise,
                    verified_title: verified_title,
                    uid: result.uid,
                    avatar_file: result.avatar_file,
                    user_name: result.user_name,
                    reputation: result.reputation,
                    agree_count: result.agree_count,
                    signature: result.signature,
                    url: result.url,
                    category_enable: result.category_enable,
                    focus: focus,
                    focusTxt: focusTxt,
                    ask_name: "'" + result.user_name + "'",
                    fans_count: result.fans_count
                  })
                );

                //判断是否为游客or自己
                if (
                  G_USER_ID == "" ||
                  G_USER_ID == result.uid ||
                  result.uid < 0
                ) {
                  $("#aw-card-tips .mod-footer").hide();
                }
                _init();
                //缓存
                AWS.G.cashUserData.push($("#aw-ajax-box").html());
              },
              "json"
            );
          }
          if (type == "topic") {
            $.get(
              G_BASE_URL + url + _this.attr("data-id"),
              function(result) {
                var focus = result.focus,
                  focusTxt;
                if (focus == false) {
                  focus = "";
                  focusTxt = _t("关注");
                } else {
                  focus = "active";
                  focusTxt = _t("取消关注");
                }
                //动态插入盒子
                $("#aw-ajax-box").html(
                  Hogan.compile(AW_TEMPLATE.topicCard).render({
                    topic_id: result.topic_id,
                    topic_pic: result.topic_pic,
                    topic_title: result.topic_title,
                    topic_description: result.topic_description,
                    discuss_count: result.discuss_count,
                    focus_count: result.focus_count,
                    focus: focus,
                    focusTxt: focusTxt,
                    url: result.url,
                    fansCount: result.fans_count
                  })
                );
                //判断是否为游客
                if (G_USER_ID == "") {
                  $("#aw-card-tips .mod-footer .follow").hide();
                }
                _init();
                //缓存
                AWS.G.cashTopicData.push($("#aw-ajax-box").html());
              },
              "json"
            );
          }
        }

        //检测缓存
        function _checkcash(type) {
          if (type == "user") {
            $.each(AWS.G.cashUserData, function(i, a) {
              if (a.match('data-id="' + _this.attr("data-id") + '"')) {
                $("#aw-ajax-box").html(a);
                $("#aw-card-tips").removeAttr("style");
                _init();
                flag = 1;
              }
            });
          }
          if (type == "topic") {
            $.each(AWS.G.cashTopicData, function(i, a) {
              if (a.match('data-id="' + _this.attr("data-id") + '"')) {
                $("#aw-ajax-box").html(a);
                $("#aw-card-tips").removeAttr("style");
                _init();
                flag = 1;
              }
            });
          }
        }

        //初始化
        function _init() {
          var left = _this.offset().left,
            top = _this.offset().top + _this.height() + 5,
            nTop = _this.offset().top - $(window).scrollTop();

          //判断下边距离不足情况
          if (nTop + $("#aw-card-tips").innerHeight() > $(window).height()) {
            top = _this.offset().top - $("#aw-card-tips").innerHeight() - 10;
          }

          //判断右边距离不足情况
          if (left + $("#aw-card-tips").innerWidth() > $(window).width()) {
            left =
              _this.offset().left -
              $("#aw-card-tips").innerWidth() +
              _this.innerWidth();
          }

          $("#aw-card-tips")
            .css({
              left: left,
              top: top
            })
            .fadeIn();
        }
      }, time);
    });

    $(document).on("mouseout", selector, function() {
      clearTimeout(AWS.G.card_box_show_timer);
      AWS.G.card_box_hide_timer = setTimeout(function() {
        $("#aw-card-tips").fadeOut();
      }, 600);
    });
  },

  // @人功能
  at_user_lists: function(selector, limit) {
    $(selector).keyup(function(e) {
      var _this = $(this),
        flag = _getCursorPosition($(this)[0]).start;
      if (
        $(this)
          .val()
          .charAt(flag - 1) == "@"
      ) {
        _init();
        $("#aw-ajax-box .content_cursor").html(
          $(this)
            .val()
            .substring(0, flag)
        );
      } else {
        var lis = $(".aw-invite-dropdown li");
        switch (e.which) {
          case 38:
            var _index;
            if (!lis.hasClass("active")) {
              lis.eq(lis.length - 1).addClass("active");
            } else {
              $.each(lis, function(i, e) {
                if ($(this).hasClass("active")) {
                  $(this).removeClass("active");
                  if ($(this).index() == 0) {
                    _index = lis.length - 1;
                  } else {
                    _index = $(this).index() - 1;
                  }
                }
              });
              lis.eq(_index).addClass("active");
            }
            break;
          case 40:
            var _index;
            if (!lis.hasClass("active")) {
              lis.eq(0).addClass("active");
            } else {
              $.each(lis, function(i, e) {
                if ($(this).hasClass("active")) {
                  $(this).removeClass("active");
                  if ($(this).index() == lis.length - 1) {
                    _index = 0;
                  } else {
                    _index = $(this).index() + 1;
                  }
                }
              });
              lis.eq(_index).addClass("active");
            }
            break;
          case 13:
            $.each($(".aw-invite-dropdown li"), function(i, e) {
              if ($(this).hasClass("active")) {
                $(this).click();
              }
            });
            break;
          default:
            if ($(".aw-invite-dropdown")[0]) {
              var ti = 0;
              for (var i = flag; i > 0; i--) {
                if (
                  $(this)
                    .val()
                    .charAt(i) == "@"
                ) {
                  ti = i;
                  break;
                }
              }
              $.get(
                G_BASE_URL +
                  "/search/ajax/search/?type=users&q=" +
                  encodeURIComponent(
                    $(this)
                      .val()
                      .substring(flag, ti)
                      .replace("@", "")
                  ) +
                  "&limit=" +
                  limit,
                function(result) {
                  if ($(".aw-invite-dropdown")[0]) {
                    if (result.length != 0) {
                      var html = "";

                      $(".aw-invite-dropdown").html("");

                      $.each(result, function(i, a) {
                        html +=
                          '<li><img src="' +
                          a.detail.avatar_file +
                          '"/><a>' +
                          a.name +
                          "</a></li>";
                      });

                      $(".aw-invite-dropdown").append(html);

                      _display();

                      $(".aw-invite-dropdown li").click(function() {
                        _this
                          .val(
                            _this.val().substring(0, ti) +
                              "@" +
                              $(this)
                                .find("a")
                                .html() +
                              " "
                          )
                          .focus();
                        $(".aw-invite-dropdown").detach();
                      });
                    } else {
                      $(".aw-invite-dropdown").hide();
                    }
                  }
                  if (_this.val().length == 0) {
                    $(".aw-invite-dropdown").hide();
                  }
                },
                "json"
              );
            }
        }
      }
    });

    $(selector).keydown(function(e) {
      var key = e.which;
      if ($(".aw-invite-dropdown").is(":visible")) {
        if (key == 38 || key == 40 || key == 13) {
          return false;
        }
      }
    });

    //初始化插入定位符
    function _init() {
      if (!$(".content_cursor")[0]) {
        $("#aw-ajax-box").append('<span class="content_cursor"></span>');
      }
      $("#aw-ajax-box")
        .find(".content_cursor")
        .css({
          left: parseInt(
            $(selector).offset().left +
              parseInt($(selector).css("padding-left")) +
              2
          ),
          top: parseInt(
            $(selector).offset().top + parseInt($(selector).css("padding-left"))
          )
        });
      if (!$(".aw-invite-dropdown")[0]) {
        $("#aw-ajax-box").append('<ul class="aw-invite-dropdown"></ul>');
      }
    }

    //初始化列表和三角型
    function _display() {
      $(".aw-invite-dropdown")
        .css({
          left:
            $(".content_cursor").offset().left +
            $(".content_cursor").innerWidth(),
          top: $(".content_cursor").offset().top + 24
        })
        .show();
    }

    //获取当前textarea光标位置
    function _getCursorPosition(textarea) {
      var rangeData = {
        text: "",
        start: 0,
        end: 0
      };

      textarea.focus();

      if (textarea.setSelectionRange) {
        // W3C
        rangeData.start = textarea.selectionStart;
        rangeData.end = textarea.selectionEnd;
        rangeData.text =
          rangeData.start != rangeData.end
            ? textarea.value.substring(rangeData.start, rangeData.end)
            : "";
      } else if (document.selection) {
        // IE
        var i,
          oS = document.selection.createRange(),
          // Don't: oR = textarea.createTextRange()
          oR = document.body.createTextRange();
        oR.moveToElementText(textarea);

        rangeData.text = oS.text;
        rangeData.bookmark = oS.getBookmark();

        // object.moveStart(sUnit [, iCount])
        // Return Value: Integer that returns the number of units moved.
        for (
          i = 0;
          oR.compareEndPoints("StartToStart", oS) < 0 &&
          oS.moveStart("character", -1) !== 0;
          i++
        ) {
          // Why? You can alert(textarea.value.length)
          if (textarea.value.charAt(i) == "\n") {
            i++;
          }
        }
        rangeData.start = i;
        rangeData.end = rangeData.text.length + rangeData.start;
      }

      return rangeData;
    }
  },

  // 错误提示效果
  shake: function(selector) {
    var length = 6;
    selector.css("position", "relative");
    for (var i = 1; i <= length; i++) {
      if (i % 2 == 0) {
        if (i == length) {
          selector.animate({ left: 0 }, 50);
        } else {
          selector.animate({ left: 10 }, 50);
        }
      } else {
        selector.animate({ left: -10 }, 50);
      }
    }
  },

  // 保留两位小数
  match_num: function(num) {
    var num = num.toString();

    if (num.indexOf(".") == -1) {
      return num;
    } else {
      num = num.substring(0, num.indexOf(".") + 3);

      return num;
    }
  }
};

// 全局变量
AWS.G = {
  cashUserData: [],
  cashTopicData: [],
  card_box_hide_timer: "",
  card_box_show_timer: "",
  dropdown_list_xhr: "",
  loading_timer: "",
  loading_bg_count: 0,
  notification_timer: "",
  countdown: {},
  countdownTimer: {}
};

AWS.User = {
  // 关注
  follow: function(selector, type, data_id) {
    selector.addClass("disabled");

    switch (type) {
      case "question":
        var url = "/question/ajax/focus/?question_id=";
        break;

      case "topic":
        var url = "/topic/ajax/focus_topic/?topic_id=";
        break;

      case "user":
        var url = "/people/ajax/follow/?uid=";
        break;
    }

    $.get(
      G_BASE_URL + url + data_id,
      function(result) {
        if (result.errno == 1) {
          if (selector.html()) {
            var span = selector.find("span");

            if (selector.hasClass("active")) {
              selector.find("b").html(parseInt(selector.find("b").html()) - 1);
            } else {
              selector.find("b").html(parseInt(selector.find("b").html()) + 1);
            }

            if (span.html().match("已关注")) {
              span.html(span.html().replace(/已关注/, "关注"));
            } else {
              span.html(span.html().replace(/关注/, "已关注"));
            }
          } else {
            if (selector.hasClass("active")) {
              selector.attr("data-original-title", _t("关注"));
            } else {
              selector.attr("data-original-title", _t("已关注"));
            }
          }

          if (result.rsm.type == "add") {
            selector.addClass("active");
          } else {
            selector.removeClass("active");
          }
        } else {
          if (result.err) {
            AWS.alert(result.err);
          }

          if (result.rsm.url) {
            window.location = result.rsm.url;
            //window.location = decodeURIComponent(result.rsm.url);
          }
        }

        selector.removeClass("disabled");
      },
      "json"
    );
  },

  share_out: function(options) {
    var url = options.url || window.location.href,
      pic = "";

    if (options.title) {
      var title = options.title + " - " + G_SITE_NAME;
    } else {
      var title = $("title").text();
    }

    shareURL =
      "http://www.jiathis.com/send/?webid=" +
      options.webid +
      "&url=" +
      url +
      "&title=" +
      title +
      "";

    if (options.content) {
      if ($(options.content).find("img").length) {
        shareURL =
          shareURL +
          "&pic=" +
          $(options.content)
            .find("img")
            .eq(0)
            .attr("src");
      }
    }

    window.open(shareURL);
  },

  // 删除草稿
  delete_draft: function(item_id, type) {
    if (type == "clean") {
      $.post(
        G_BASE_URL + "/account/ajax/delete_draft/",
        "type=" + type,
        function(result) {
          if (result.errno != 1) {
            AWS.alert(result.err);
          }
        },
        "json"
      );
    } else {
      $.post(
        G_BASE_URL + "/account/ajax/delete_draft/",
        "item_id=" + item_id + "&type=" + type,
        function(result) {
          if (result.errno != 1) {
            AWS.alert(result.err);
          }
        },
        "json"
      );
    }
  },

  // 赞成投票
  agree_vote: function(selector, user_name, answer_id, type) {
    var url = G_BASE_URL + "/question/ajax/answer_vote/";

    if (type == "crowdsourcing") {
      url = G_BASE_URL + "/crowdsourcing/ajax/answer_vote/";
    }

    $.post(url, "answer_id=" + answer_id + "&value=1");

    // 判断是否投票过
    if ($(selector).hasClass("active")) {
      if (
        $(selector)
          .parents(".item")
          .find(".aw-agree-by")
          .text()
          .match(user_name)
      ) {
        $.each(
          $(selector)
            .parents(".item")
            .find(".aw-agree-by a"),
          function(i, e) {
            if ($(e).html() == user_name) {
              if ($(e).prev()) {
                $(e)
                  .prev()
                  .remove();
              } else {
                $(e)
                  .next()
                  .remove();
              }

              $(e).remove();
            }
          }
        );
      }

      if (
        parseInt(
          $(selector)
            .parents(".operate")
            .find(".count")
            .html()
        ) != 0
      ) {
        $(selector)
          .parents(".operate")
          .find(".count")
          .html(
            parseInt(
              $(selector)
                .parents(".operate")
                .find(".count")
                .html()
            ) - 1
          );
      }

      if (
        $(selector)
          .parents(".item")
          .find(".aw-agree-by a").length == 0
      ) {
        $(selector)
          .parents(".item")
          .find(".aw-agree-by")
          .hide();
      }

      $(selector).removeClass("active");
    } else {
      // 判断是否第一个投票
      if (
        $(selector)
          .parents(".item")
          .find(".aw-agree-by a").length == 0
      ) {
        $(selector)
          .parents(".item")
          .find(".aw-agree-by")
          .append('<a class="aw-user-name color-999">' + user_name + "</a>");
      } else {
        $(selector)
          .parents(".item")
          .find(".aw-agree-by")
          .append(
            '<em>、</em><a class="aw-user-name color-999">' + user_name + "</a>"
          );
      }

      $(selector)
        .parents(".operate")
        .find(".count")
        .html(
          parseInt(
            $(selector)
              .parents(".operate")
              .find(".count")
              .html()
          ) + 1
        );

      $(selector)
        .parents(".item")
        .find(".aw-agree-by")
        .show();

      $(selector)
        .parents(".operate")
        .find("a.active")
        .removeClass("active");

      $(selector).addClass("active");
    }
  },

  // 反对投票
  disagree_vote: function(selector, user_name, answer_id, type) {
    var url = G_BASE_URL + "/question/ajax/answer_vote/";

    if (type == "crowdsourcing") {
      url = G_BASE_URL + "/crowdsourcing/ajax/answer_vote/";
    }

    $.post(url, "answer_id=" + answer_id + "&value=-1", function(result) {});

    if ($(selector).hasClass("active")) {
      $(selector).removeClass("active");
    } else {
      // 判断是否有赞同过
      if (
        $(selector)
          .parents(".operate")
          .find(".agree")
          .hasClass("active")
      ) {
        // 删除赞同操作
        $.each(
          $(selector)
            .parents(".aw-item")
            .find(".aw-user-name"),
          function(i, e) {
            if ($(e).html() == user_name) {
              if ($(e).prev()) {
                $(e)
                  .prev()
                  .remove();
              } else {
                $(e)
                  .next()
                  .remove();
              }

              $(e).remove();
            }
          }
        );

        // 判断赞同来自内是否有人
        if (
          $(selector)
            .parents(".aw-item")
            .find(".aw-agree-by a").length == 0
        ) {
          $(selector)
            .parents(".aw-item")
            .find(".aw-agree-by")
            .hide();
        }

        $(selector)
          .parents(".operate")
          .find(".count")
          .html(
            parseInt(
              $(selector)
                .parents(".operate")
                .find(".count")
                .html()
            ) - 1
          );

        $(selector)
          .parents(".operate")
          .find(".agree")
          .removeClass("active");

        $(selector).addClass("active");
      } else {
        $(selector).addClass("active");
      }
    }
  },

  // 问题不感兴趣
  question_uninterested: function(selector, question_id) {
    selector.fadeOut();

    $.post(
      G_BASE_URL + "/question/ajax/uninterested/",
      "question_id=" + question_id,
      function(result) {
        if (result.errno != "1") {
          AWS.alert(result.err);
        }
      },
      "json"
    );
  },

  // 回复折叠
  answer_force_fold: function(selector, answer_id) {
    $.post(
      G_BASE_URL + "/question/ajax/answer_force_fold/",
      "answer_id=" + answer_id,
      function(result) {
        if (result.errno != 1) {
          AWS.alert(result.err);
        } else if (result.errno == 1) {
          if (result.rsm.action == "fold") {
            selector.html(selector.html().replace(_t("折叠"), _t("撤消折叠")));
          } else {
            selector.html(selector.html().replace(_t("撤消折叠"), _t("折叠")));
          }
        }
      },
      "json"
    );
  },

  // 删除别人邀请我回复的问题
  question_invite_delete: function(selector, question_invite_id) {
    $.post(
      G_BASE_URL + "/question/ajax/question_invite_delete/",
      "question_invite_id=" + question_invite_id,
      function(result) {
        if (result.errno == 1) {
          selector.fadeOut();
        } else {
          AWS.alert(result.rsm.err);
        }
      },
      "json"
    );
  },

  // 邀请用户回答问题
  invite_user: function(selector, img) {
    $.post(
      G_BASE_URL + "/question/ajax/save_invite/",
      {
        question_id: QUESTION_ID,
        uid: selector.attr("data-id")
      },
      function(result) {
        if (result.errno != -1) {
          if (
            selector.parents(".aw-invite-box").find(".invite-list a").length ==
            0
          ) {
            selector
              .parents(".aw-invite-box")
              .find(".invite-list")
              .show();
          }
          selector
            .parents(".aw-invite-box")
            .find(".invite-list")
            .append(
              ' <a class="text-color-999 invite-list-user" data-toggle="tooltip" data-placement="bottom" data-original-title="' +
                selector.attr("data-value") +
                '"><img src=' +
                img +
                " /></a>"
            );
          selector
            .addClass("active")
            .attr("onclick", "AWS.User.disinvite_user($(this))")
            .text("取消邀请");
          selector
            .parents(".aw-question-detail")
            .find(".aw-invite-replay .badge")
            .text(
              parseInt(
                selector
                  .parents(".aw-question-detail")
                  .find(".aw-invite-replay .badge")
                  .text()
              ) + 1
            );
        } else if (result.errno == -1) {
          AWS.alert(result.err);
        }
      },
      "json"
    );
  },

  // 取消邀请用户回答问题
  disinvite_user: function(selector) {
    $.get(
      G_BASE_URL +
        "/question/ajax/cancel_question_invite/question_id-" +
        QUESTION_ID +
        "__recipients_uid-" +
        selector.attr("data-id"),
      function(result) {
        if (result.errno != -1) {
          $.each($(".aw-question-detail .invite-list a"), function(i, e) {
            if (
              $(this).attr("data-original-title") ==
              selector
                .parents(".main")
                .find(".aw-user-name")
                .text()
            ) {
              $(this).detach();
            }
          });
          selector
            .removeClass("active")
            .attr(
              "onclick",
              "AWS.User.invite_user($(this),$(this).parents('li').find('img').attr('src'))"
            )
            .text("邀请");
          selector
            .parents(".aw-question-detail")
            .find(".aw-invite-replay .badge")
            .text(
              parseInt(
                selector
                  .parents(".aw-question-detail")
                  .find(".aw-invite-replay .badge")
                  .text()
              ) - 1
            );
          if (
            selector
              .parents(".aw-invite-box")
              .find(".invite-list")
              .children().length == 0
          ) {
            selector
              .parents(".aw-invite-box")
              .find(".invite-list")
              .hide();
          }
        }
      }
    );
  },

  // 问题感谢
  // Modify by wegene
  question_thanks: function(selector, question_id) {
    $.post(
      G_BASE_URL + "/question/ajax/question_thanks/",
      "question_id=" + question_id,
      function(result) {
        if (result.errno != 1) {
          AWS.alert(result.err);
        } else if (result.rsm.action == "add") {
          selector.addClass("active");
          selector
            .find("span")
            .html(parseInt(selector.find("span").html()) + 1);

          // selector.html(selector.html().replace(_t('感谢'), _t('已感谢')));
          // selector.removeAttr('onclick');
        } else {
          selector.removeClass("active");
          selector
            .find("span")
            .html(parseInt(selector.find("span").html()) - 1);
        }
      },
      "json"
    );
  },

  // 感谢评论回复者
  answer_user_rate: function(selector, type, answer_id) {
    $.post(
      G_BASE_URL + "/question/ajax/question_answer_rate/",
      "type=" + type + "&answer_id=" + answer_id,
      function(result) {
        if (result.errno != 1) {
          AWS.alert(result.err);
        } else if (result.errno == 1) {
          switch (type) {
            case "thanks":
              if (result.rsm.action == "add") {
                selector.html(
                  selector.html().replace(_t("感谢"), _t("已感谢"))
                );
                selector.removeAttr("onclick");
              } else {
                selector.html(
                  selector.html().replace(_t("已感谢"), _t("感谢"))
                );
              }
              break;

            case "uninterested":
              if (result.rsm.action == "add") {
                selector.html(
                  selector.html().replace(_t("没有帮助"), _t("撤消没有帮助"))
                );
              } else {
                selector.html(
                  selector.html().replace(_t("撤消没有帮助"), _t("没有帮助"))
                );
              }
              break;
          }
        }
      },
      "json"
    );
  },

  // 提交评论
  save_comment: function(selector) {
    selector.addClass("disabled");

    AWS.ajax_post(
      selector.parents("form"),
      AWS.ajax_processer,
      "comments_form"
    );
  },

  // 删除评论
  remove_comment: function(selector, type, comment_id) {
    $.get(
      G_BASE_URL +
        "/question/ajax/remove_comment/type-" +
        type +
        "__comment_id-" +
        comment_id
    );

    selector.parents(".aw-comment-box li").fadeOut();
  },

  // 文章赞同
  article_vote: function(selector, article_id, rating) {
    AWS.loading("show");

    if (selector.hasClass("active")) {
      var rating = 0;
    }

    $.post(
      G_BASE_URL + "/article/ajax/article_vote/",
      "type=article&item_id=" + article_id + "&rating=" + rating,
      function(result) {
        AWS.loading("hide");

        if (result.errno != 1) {
          AWS.alert(result.err);
        } else {
          if (rating == 0) {
            selector
              .removeClass("active")
              .find("b")
              .html(parseInt(selector.find("b").html()) - 1);
          } else if (rating == -1) {
            if (
              selector
                .parents(".aw-article-vote")
                .find(".agree")
                .hasClass("active")
            ) {
              selector
                .parents(".aw-article-vote")
                .find("b")
                .html(
                  parseInt(
                    selector
                      .parents(".aw-article-vote")
                      .find("b")
                      .html()
                  ) - 1
                );
              selector
                .parents(".aw-article-vote")
                .find("a")
                .removeClass("active");
            }

            selector.addClass("active");
          } else {
            selector
              .parents(".aw-article-vote")
              .find("a")
              .removeClass("active");
            selector
              .addClass("active")
              .find("b")
              .html(parseInt(selector.find("b").html()) + 1);
          }
        }
      },
      "json"
    );
  },

  // 文章评论赞同
  article_comment_vote: function(selector, comment_id, rating) {
    AWS.loading("show");

    if (selector.hasClass("active")) {
      var rating = 0;
    }

    $.post(
      G_BASE_URL + "/article/ajax/article_vote/",
      "type=comment&item_id=" + comment_id + "&rating=" + rating,
      function(result) {
        AWS.loading("hide");

        if (result.errno != 1) {
          AWS.alert(result.err);
        } else {
          if (rating == 0) {
            selector
              .html(selector.html().replace(_t("我已赞"), _t("赞")))
              .removeClass("active");
          } else {
            selector
              .html(selector.html().replace(_t("赞"), _t("我已赞")))
              .addClass("active");
          }
        }
      },
      "json"
    );
  },

  // 创建收藏标签
  add_favorite_tag: function() {
    $.post(
      G_BASE_URL + "/favorite/ajax/update_favorite_tag/",
      {
        item_id: $('#favorite_form input[name="item_id"]').val(),
        item_type: $('#favorite_form input[name="item_type"]').val(),
        tags: $("#favorite_form .add-input").val()
      },
      function(result) {
        if (result.errno == 1) {
          $(".aw-favorite-box .aw-favorite-tag-list").show();
          $(".aw-favorite-box .aw-favorite-tag-add").hide();

          $(".aw-favorite-tag-list ul").prepend(
            '<li class="active"><a data-value="' +
              $("#favorite_form .add-input").val() +
              '"><span class="title">' +
              $("#favorite_form .add-input").val() +
              '</span></a><i class="icon icon-followed"></i></li>'
          );
        }
      },
      "json"
    );
  },

  // 更换邮箱
  change_email: function(element) {
    $.post(
      G_BASE_URL + "/account/ajax/modify_unvalid_email/",
      {
        email: element.find("input").val()
      },
      function(result) {
        AWS.alert(result.err);

        element.hide();

        element.find("input").val("");
      },
      "json"
    );
  }
};

AWS.Dropdown = {
  // 下拉菜单功能绑定
  bind_dropdown_list: function(selector, type) {
    if (type == "search") {
      $(selector).focus(function() {
        $(selector)
          .parent()
          .find(".aw-dropdown")
          .show();
      });
    }
    $(selector).keyup(function(e) {
      if (type == "search") {
        $(selector)
          .parent()
          .find(".search")
          .show()
          .children("a")
          .text($(selector).val());
      }
      if ($(selector).val().length >= 1) {
        if (e.which != 38 && e.which != 40 && e.which != 188 && e.which != 13) {
          AWS.Dropdown.get_dropdown_list($(this), type, $(selector).val());
        }
      } else {
        $(selector)
          .parent()
          .find(".aw-dropdown")
          .hide();
      }

      if (type == "topic") {
        // 逗号或回车提交
        if (e.which == 188) {
          if ($(".aw-edit-topic-box #aw_edit_topic_title").val() != ",") {
            $(".aw-edit-topic-box #aw_edit_topic_title").val(
              $(".aw-edit-topic-box #aw_edit_topic_title")
                .val()
                .substring(
                  0,
                  $(".aw-edit-topic-box #aw_edit_topic_title").val().length - 1
                )
            );
            $(".aw-edit-topic-box .aw-dropdown").hide();
            $(".aw-edit-topic-box .add").click();
          }
          return false;
        }

        // 回车提交
        if (e.which == 13) {
          $(".aw-edit-topic-box .aw-dropdown").hide();
          $(".aw-edit-topic-box .add").click();
          return false;
        }

        var lis = $(selector)
          .parent()
          .find(".aw-dropdown-list li");

        //键盘往下
        if (e.which == 40 && lis.is(":visible")) {
          var _index;
          if (!lis.hasClass("active")) {
            lis.eq(0).addClass("active");
          } else {
            $.each(lis, function(i, e) {
              if ($(this).hasClass("active")) {
                $(this).removeClass("active");
                if ($(this).index() == lis.length - 1) {
                  _index = 0;
                } else {
                  _index = $(this).index() + 1;
                }
              }
            });
            lis.eq(_index).addClass("active");
            $(selector).val(lis.eq(_index).text());
          }
        }

        //键盘往上
        if (e.which == 38 && lis.is(":visible")) {
          var _index;
          if (!lis.hasClass("active")) {
            lis.eq(lis.length - 1).addClass("active");
          } else {
            $.each(lis, function(i, e) {
              if ($(this).hasClass("active")) {
                $(this).removeClass("active");
                if ($(this).index() == 0) {
                  _index = lis.length - 1;
                } else {
                  _index = $(this).index() - 1;
                }
              }
            });
            lis.eq(_index).addClass("active");
            $(selector).val(lis.eq(_index).text());
          }
        }
      }
    });

    $(selector).blur(function() {
      $(selector)
        .parent()
        .find(".aw-dropdown")
        .delay(500)
        .fadeOut(300);
    });
  },

  // 插入下拉菜单
  set_dropdown_list: function(selector, data, selected) {
    $(selector).append(
      Hogan.compile(AW_TEMPLATE.dropdownList).render({
        items: data
      })
    );

    $(selector + " .aw-dropdown-list li a").click(function() {
      $("#aw-topic-tags-select").html($(this).text());
    });

    if (selected) {
      $(
        selector + " .dropdown-menu li a[data-value='" + selected + "']"
      ).click();
    }
  },

  /* 下拉菜单数据获取 */
  /*
   *    type : search, publish, redirect, invite, inbox, topic_question, topic
   */
  get_dropdown_list: function(selector, type, data) {
    if (AWS.G.dropdown_list_xhr != "") {
      AWS.G.dropdown_list_xhr.abort(); // 中止上一次ajax请求
    }
    var url;
    switch (type) {
      case "search":
        url =
          G_BASE_URL +
          "/search/ajax/search/?q=" +
          encodeURIComponent(data) +
          "&limit=5";
        break;

      case "publish":
        url =
          G_BASE_URL +
          "/search/ajax/search/?type=questions&q=" +
          encodeURIComponent(data) +
          "&limit=5";
        break;

      case "redirect":
        url =
          G_BASE_URL +
          "/search/ajax/search/?q=" +
          encodeURIComponent(data) +
          "&type=questions&limit=30";
        break;

      case "invite":
      case "inbox":
        url =
          G_BASE_URL +
          "/search/ajax/search/?type=users&q=" +
          encodeURIComponent(data) +
          "&limit=10";
        break;

      case "topic_question":
        url =
          G_BASE_URL +
          "/search/ajax/search/?type=questions,articles&q=" +
          encodeURIComponent(data) +
          "&topic_ids=" +
          CONTENTS_RELATED_TOPIC_IDS +
          "&limit=50";
        break;

      case "topic":
        url =
          G_BASE_URL +
          "/search/ajax/search/?type=topics&q=" +
          encodeURIComponent(data) +
          "&limit=10";
        break;

      case "questions":
        url =
          G_BASE_URL +
          "/search/ajax/search/?type=questions&q=" +
          encodeURIComponent(data) +
          "&limit=10";
        break;

      case "articles":
        url =
          G_BASE_URL +
          "/search/ajax/search/?type=articles&q=" +
          encodeURIComponent(data) +
          "&limit=10";
        break;
    }

    AWS.G.dropdown_list_xhr = $.get(
      url,
      function(result) {
        if (result.length != 0 && AWS.G.dropdown_list_xhr != undefined) {
          $(selector)
            .parent()
            .find(".aw-dropdown-list")
            .html(""); // 清空内容
          switch (type) {
            case "search":
              $.each(result, function(i, a) {
                switch (a.type) {
                  case "questions":
                    if (a.detail.best_answer > 0) {
                      var active = "active";
                    } else {
                      var active = "";
                    }

                    $(selector)
                      .parent()
                      .find(".aw-dropdown-list")
                      .append(
                        Hogan.compile(
                          AW_TEMPLATE.searchDropdownListQuestions
                        ).render({
                          url: a.url,
                          active: active,
                          content: a.name,
                          discuss_count: a.detail.answer_count
                        })
                      );
                    break;

                  case "articles":
                    $(selector)
                      .parent()
                      .find(".aw-dropdown-list")
                      .append(
                        Hogan.compile(
                          AW_TEMPLATE.searchDropdownListArticles
                        ).render({
                          url: a.url,
                          content: a.name,
                          comments: a.detail.comments
                        })
                      );
                    break;

                  case "topics":
                    $(selector)
                      .parent()
                      .find(".aw-dropdown-list")
                      .append(
                        Hogan.compile(
                          AW_TEMPLATE.searchDropdownListTopics
                        ).render({
                          url: a.url,
                          name: a.name,
                          discuss_count: a.detail.discuss_count,
                          topic_id: a.detail.topic_id
                        })
                      );
                    break;

                  case "users":
                    if (a.detail.signature == "") {
                      var signature = _t("暂无介绍");
                    } else {
                      var signature = a.detail.signature;
                    }

                    $(selector)
                      .parent()
                      .find(".aw-dropdown-list")
                      .append(
                        Hogan.compile(
                          AW_TEMPLATE.searchDropdownListUsers
                        ).render({
                          url: a.url,
                          img: a.detail.avatar_file,
                          name: a.name,
                          intro: signature
                        })
                      );
                    break;
                }
              });
              break;

            case "publish":
            case "topic_question":
              $.each(result, function(i, a) {
                $(selector)
                  .parent()
                  .find(".aw-dropdown-list")
                  .append(
                    Hogan.compile(AW_TEMPLATE.questionDropdownList).render({
                      url: a.url,
                      name: a.name
                    })
                  );
              });
              break;

            case "topic":
              $.each(result, function(i, a) {
                $(selector)
                  .parent()
                  .find(".aw-dropdown-list")
                  .append(
                    Hogan.compile(AW_TEMPLATE.editTopicDorpdownList).render({
                      name: a["name"]
                    })
                  );
              });
              break;

            case "redirect":
              $.each(result, function(i, a) {
                $(selector)
                  .parent()
                  .find(".aw-dropdown-list")
                  .append(
                    Hogan.compile(AW_TEMPLATE.questionRedirectList).render({
                      url:
                        "'" +
                        G_BASE_URL +
                        "/question/ajax/redirect/', 'item_id=" +
                        $(selector).attr("data-id") +
                        "&target_id=" +
                        a["search_id"] +
                        "'",
                      name: a["name"]
                    })
                  );
              });
              break;

            case "questions":
            case "articles":
              $.each(result, function(i, a) {
                $(selector)
                  .parent()
                  .find(".aw-dropdown-list")
                  .append(
                    Hogan.compile(AW_TEMPLATE.questionDropdownList).render({
                      url: "#",
                      name: a["name"]
                    })
                  );
              });
              break;

              $(selector)
                .parent()
                .find(".aw-dropdown-list li")
                .click(function() {
                  $(".aw-question-list").append(
                    '<li data-id="' +
                      $(this).attr("data-id") +
                      '"><div class="col-sm-9">' +
                      $(this).html() +
                      '</div> <div class="col-sm-3"><a class="btn btn-danger btn-xs">删除</a></div></li>'
                  );

                  $(".aw-question-list li")
                    .find("a")
                    .attr("href", function() {
                      return $(this).attr("_href");
                    });

                  if ($(".question_ids").val() == "") {
                    $(".question_ids").val($(this).attr("data-id") + ",");
                  } else {
                    $(".question_ids").val(
                      $(".question_ids").val() + $(this).attr("data-id") + ","
                    );
                  }
                  $(".alert-box").modal("hide");
                });

              break;

            case "inbox":
            case "invite":
              $.each(result, function(i, a) {
                $(selector)
                  .parent()
                  .find(".aw-dropdown-list")
                  .append(
                    Hogan.compile(AW_TEMPLATE.inviteDropdownList).render({
                      uid: a.uid,
                      name: a.name,
                      img: a.detail.avatar_file
                    })
                  );
              });
              break;
          }
          if (type == "publish") {
            $(selector)
              .parent()
              .find(
                ".aw-publish-suggest-question, .aw-publish-suggest-question .aw-dropdown-list"
              )
              .show();
          } else {
            $(selector)
              .parent()
              .find(".aw-dropdown, .aw-dropdown-list")
              .show()
              .children()
              .show();
            $(selector)
              .parent()
              .find(".title")
              .hide();
            // 关键词高亮
            $(selector)
              .parent()
              .find(".aw-dropdown-list li.question a")
              .highText(data, "b", "active");
          }
        } else {
          $(selector)
            .parent()
            .find(".aw-dropdown")
            .show()
            .end()
            .find(".title")
            .html(_t("没有找到相关结果"))
            .show();
          $(selector)
            .parent()
            .find(".aw-dropdown-list, .aw-publish-suggest-question")
            .hide();
        }
      },
      "json"
    );
  }
};

AWS.Editor = {
  // 设置编辑器预览状态
  set_editor_preview: function() {
    if ($.cookie("data_editor_preview") == "true") {
      $(".icon-preview")
        .parents("button")
        .addClass("active");

      $(".wmd-preview").fadeIn();
    } else {
      $(".icon-preview")
        .parents("button")
        .removeClass("active");

      $(".wmd-preview").fadeOut();
    }
  },

  // 向编辑器插入多媒体内容(图片,视频,超链接)
  add_multimedia: function(type) {
    switch (type) {
      case "img":
        var title = "imgsAlt",
          url = "imgsUrl",
          textFeildValue =
            "![请输入图片名字](" +
            $('#addTxtForms :input[name="' + url + '"]').val() +
            ")";
        break;

      case "video":
        var title = "videoTitle",
          url = "videoUrl",
          textFeildValue =
            "!![" +
            $('#addTxtForms :input[name="' + title + '"]').val() +
            "](" +
            $('#addTxtForms :input[name="' + url + '"]').val() +
            ")";
        break;

      case "link":
        var title = "linkText",
          url = "linkUrl",
          textFeildValue =
            "[" +
            $('#addTxtForms :input[name="' + title + '"]').val() +
            "](" +
            $('#addTxtForms :input[name="' + url + '"]').val() +
            ")";
        break;
    }
    if ($('#addTxtForms :input[name="' + url + '"]').val() == "") {
      return false;
    }

    $(".wmd-input").insertAtCaret(textFeildValue);

    chunk.selection = (" " + chunk.selection)
      .replace(/([^\\](?:\\\\)*)(?=[[\]])/g, "$1\\")
      .substr(1);
  },

  // 向编辑器插入文本
  insert_into_codemirror: function(fn) {
    var flag = false,
      pos = {},
      cursor = 0,
      textarea = $(".advanced_editor");
    if (advanced_editor != null) {
      pos = advanced_editor.getCursor("start");

      advanced_editor.toTextArea();

      for (var i = 0, iLen = pos.line; i < iLen; i++) {
        cursor += advanced_editor.lineInfo(i).text.length + 1;
      }

      cursor += pos.ch;

      if (textarea.createTextRange) {
        // quick fix to make it work on Opera 9.5
        /*if ($.browser.opera && $.browser.version >= 9.5 && advanced_editor.getSelection().length == 0)
					{
						return false;
					}*/
        range = textarea.createTextRange();
        range.collapse(true);
        range.moveStart("character", cursor);
        range.moveEnd("character", advanced_editor.getSelection().length);
        range.select();
      } else if (textarea.setSelectionRange) {
        textarea.setSelectionRange(
          cursor,
          cursor + advanced_editor.getSelection().length
        );
      }
      textarea.focus();
      advanced_editor = null;
      flag = true;
    }

    fn(arguments[1]);

    if (flag) {
      advanced_editor = CodeMirror.fromTextArea(textarea, {
        mode: "markdown",
        lineNumbers: true,
        theme: "default",
        extraKeys: {
          Enter: "newlineAndIndentContinueMarkdownList"
        }
      });

      if (
        typeof arguments[1] != "undefined" &&
        (arguments[1].offset || arguments[1].addline)
      ) {
        pos.line += arguments[1].addline ? arguments[1].addline : 0;
        pos.ch += arguments[1].offset ? arguments[1].offset : 0;
      }

      advanced_editor.setCursor(pos);
    }
  },

  // 编辑器插入附件
  insert_attach: function(selector, attach_id, attach_tag) {
    selector
      .parents("form")
      .find("textarea")
      .insertAtCaret(
        "\n[" + attach_tag + "]" + attach_id + "[/" + attach_tag + "]\n"
      );
  }
};

AWS.Message = {
  // Modify by wecenter
  // 检测通知
  check_notifications: function() {
    // 检测登录状态
    if (G_USER_ID == 0) {
      clearInterval(AWS.G.notification_timer);
      return false;
    }

    $.get(
      G_BASE_URL + "/home/ajax/notifications/",
      function(result) {
        $(".inbox_unread").html(Number(result.rsm.inbox_num));

        var last_unread_notification = G_UNREAD_NOTIFICATION;

        G_UNREAD_NOTIFICATION = Number(result.rsm.notifications_num);

        if (G_UNREAD_NOTIFICATION > 0) {
          if (G_UNREAD_NOTIFICATION != last_unread_notification) {
            // 加载消息列表
            //AWS.Message.load_notification_list();

            // 给导航label添加未读消息数量
            $(".notifications_unread").html(G_UNREAD_NOTIFICATION);
          }

          if (!$("title").hasClass("notedit")) {
            document.title =
              "(" +
              (Number(result.rsm.notifications_num) +
                Number(result.rsm.inbox_num)) +
              ") " +
              document_title;
          }

          $(".notifications_unread").show();
        } else {
          if ($("#header_notification_list").length) {
            $("#header_notification_list").html(
              '<p class="aw-padding10" align="center">' +
                _t("没有未读通知") +
                "</p>"
            );
          }

          if ($("#index_notification").length) {
            $("#index_notification").fadeOut();
          }

          document.title = document_title;

          $(".notifications_unread").hide();
        }

        // 私信
        if (Number(result.rsm.inbox_num) > 0) {
          $(".inbox_unread").show();
        } else {
          $(".inbox_unread").hide();
        }
      },
      "json"
    );
  },

  // 阅读通知
  read_notification: function(selector, notification_id, reload) {
    if (notification_id) {
      selector
        .parents(".item")
        .find(".circle")
        .remove();

      selector.remove();

      var url =
        G_BASE_URL +
        "/notifications/ajax/read_notification/notification_id-" +
        notification_id;
    } else {
      if ($("#index_notification").length) {
        $("#index_notification").fadeOut();
      }

      var url = G_BASE_URL + "/notifications/ajax/read_notification/";
    }

    $.get(url, function(result) {
      AWS.Message.check_notifications();

      if (reload) {
        window.location.reload();
      }
    });
  },

  // 重新加载通知列表
  load_notification_list: function() {
    if ($("#index_notification").length) {
      // 给首页通知box内label添加未读消息数量
      $("#index_notification")
        .fadeIn()
        .find("[name=notification_unread_num]")
        .html(G_UNREAD_NOTIFICATION);

      $("#index_notification ul#notification_list").html(
        '<p align="center" style="padding: 15px 0"><img src="' +
          G_STATIC_URL +
          '/common/loading_b.gif"/></p>'
      );

      $.get(G_BASE_URL + "/notifications/ajax/list/flag-0__page-0", function(
        result
      ) {
        $("#index_notification ul#notification_list").html(result);

        AWS.Message.notification_show(5);
      });
    }

    if ($("#header_notification_list").length) {
      $.get(
        G_BASE_URL +
          "/notifications/ajax/list/flag-0__limit-5__template-header_list",
        function(result) {
          if (result.length) {
            $("#header_notification_list").html(result);
          } else {
            $("#header_notification_list").html(
              '<p class="aw-padding10" align="center">' +
                _t("没有未读通知") +
                "</p>"
            );
          }
        }
      );
    }
  },

  // 控制通知数量
  notification_show: function(length) {
    if ($("#index_notification").length > 0) {
      if ($("#index_notification ul#notification_list li").length == 0) {
        $("#index_notification").fadeOut();
      } else {
        $("#index_notification ul#notification_list li").each(function(i, e) {
          if (i < length) {
            $(e).show();
          } else {
            $(e).hide();
          }
        });
      }
    }
  }
};

AWS.Init = {
  // 初始化问题评论框
  init_comment_box: function(selector, is_lock) {
    $(document).on("click", selector, function() {
      $(this)
        .parents(".aw-question-detail")
        .find(".aw-invite-box, .aw-question-related-box")
        .hide();
      if (typeof COMMENT_UNFOLD != "undefined") {
        if (
          COMMENT_UNFOLD == "all" &&
          $(this).attr("data-comment-count") == 0 &&
          $(this).attr("data-first-click") == "hide"
        ) {
          $(this).removeAttr("data-first-click");
          return false;
        }
      }

      if (!$(this).attr("data-type") || !$(this).attr("data-id")) {
        return true;
      }

      var comment_box_id =
        "#aw-comment-box-" +
        $(this).attr("data-type") +
        "-" +
        $(this).attr("data-id");

      if ($(comment_box_id).length) {
        if ($(comment_box_id).css("display") == "none") {
          $(this).addClass("active");

          $(comment_box_id).fadeIn();
        } else {
          $(this).removeClass("active");
          $(comment_box_id).fadeOut();
        }
      } else {
        // 动态插入commentBox
        switch ($(this).attr("data-type")) {
          case "question":
            var comment_form_action =
              G_BASE_URL +
              "/question/ajax/save_question_comment/question_id-" +
              $(this).attr("data-id");
            var comment_data_url =
              G_BASE_URL +
              "/question/ajax/get_question_comments/question_id-" +
              $(this).attr("data-id");
            break;

          case "answer":
            var comment_form_action =
              G_BASE_URL +
              "/question/ajax/save_answer_comment/answer_id-" +
              $(this).attr("data-id");
            var comment_data_url =
              G_BASE_URL +
              "/question/ajax/get_answer_comments/answer_id-" +
              $(this).attr("data-id");
            break;

          case "crowdsourcing_answer":
            var comment_form_action =
              G_BASE_URL +
              "/crowdsourcing/ajax/save_answer_comment/answer_id-" +
              $(this).attr("data-id");
            var comment_data_url =
              G_BASE_URL +
              "/crowdsourcing/ajax/get_answer_comments/answer_id-" +
              $(this).attr("data-id");
            break;
            break;
        }

        if (G_USER_ID) {
          $(this)
            .parents(".item")
            .find(".mod-footer")
            .append(
              Hogan.compile(AW_TEMPLATE.commentBox).render({
                comment_form_id: comment_box_id.replace("#", ""),
                comment_form_action: comment_form_action,
                is_lock: QUESTION_LOCK ? "hide" : ""
              })
            );

          // 手机验证
          if (G_MOBILE_VALID == 1) {
            $(comment_box_id)
              .find(".aw-comment-txt")
              .bind({
                focus: function() {
                  $(comment_box_id)
                    .find(".control")
                    .show();
                },

                blur: function() {
                  if ($(this).val() == "") {
                    $(comment_box_id)
                      .find(".control")
                      .hide();
                  }
                }
              });

            $(comment_box_id)
              .find(".close-comment-box")
              .click(function() {
                $(comment_box_id).fadeOut();
                $(comment_box_id)
                  .find(".aw-comment-txt")
                  .css("height", $(this).css("line-height"));
              });
          } else {
            $(comment_box_id)
              .find("form")
              .detach();
            $(comment_box_id).append(
              '<div class="text-center">请验证您的手机以使用社区功能。 <a href="account2/setting/">前往设置</a ></div>'
            );
          }
        } else {
          $(this)
            .parents(".item")
            .find(".mod-footer")
            .append(
              Hogan.compile(AW_TEMPLATE.commentBoxClose).render({
                comment_form_id: comment_box_id.replace("#", ""),
                comment_form_action: comment_form_action
              })
            );
        }

        // 判断是否有评论数据
        $.get(comment_data_url, function(result) {
          if ($.trim(result) == "") {
            result =
              '<div align="center" class="padding-10" style="border-bottom:1px solid #eceff1;">' +
              _t("暂无评论") +
              "</div>";
          }

          $(comment_box_id)
            .find(".aw-comment-list")
            .html(result);
        });

        // textarae自动增高
        $(comment_box_id)
          .find(".aw-comment-txt")
          .autosize();

        $(this).addClass("active");

        AWS.at_user_lists(comment_box_id + " .aw-comment-txt", 5);
      }
    });
  },

  // 初始化文章评论框
  init_article_comment_box: function(selector) {
    $(document).on("click", selector, function() {
      var _editor_box = $(this)
        .parents(".aw-item")
        .find(".aw-article-replay-box");
      if (_editor_box.length) {
        if (_editor_box.css("display") == "block") {
          _editor_box.fadeOut();
        } else {
          _editor_box.fadeIn();
        }
      } else {
        $(this)
          .parents(".mod-footer")
          .append(
            Hogan.compile(AW_TEMPLATE.articleCommentBox).render({
              at_uid: $(this).attr("data-id"),
              article_id: $(".aw-topic-bar").attr("data-id")
            })
          );
      }
    });
  },

  // 初始化话题编辑box
  init_topic_edit_box: function(
    selector //selector -> .aw-edit-topic
  ) {
    $(selector).click(function() {
      var _topic_editor = $(this).parents(".aw-topic-bar"),
        data_id = _topic_editor.attr("data-id"),
        data_type = _topic_editor.attr("data-type");

      if (!_topic_editor.hasClass("active")) {
        _topic_editor.addClass("active");

        if (!_topic_editor.find(".topic-tag .close").length) {
          _topic_editor
            .find(".topic-tag")
            .append('<a class="close"><i class="icon icon-delete"></i></a>');
        }
      } else {
        _topic_editor.addClass("active");
      }

      // 判断插入编辑box
      if (_topic_editor.find(".aw-edit-topic-box").length == 0) {
        _topic_editor.append(AW_TEMPLATE.editTopicBox);

        // 给编辑box添加按钮添加事件
        _topic_editor.find(".add").click(function() {
          if (_topic_editor.find("#aw_edit_topic_title").val() != "") {
            switch (data_type) {
              case "publish":
                _topic_editor
                  .find(".tag-bar")
                  .prepend(
                    '<span class="topic-tag"><a class="text">' +
                      _topic_editor.find("#aw_edit_topic_title").val() +
                      '</a><a class="close" onclick="$(this).parents(\'.topic-tag\').remove();"><i class="icon icon-delete"></i></a><input type="hidden" value="' +
                      _topic_editor.find("#aw_edit_topic_title").val() +
                      '" name="topics[]" /></span>'
                  )
                  .hide()
                  .fadeIn();

                _topic_editor.find("#aw_edit_topic_title").val("");
                break;

              case "question":
                $.post(
                  G_BASE_URL + "/topic/ajax/save_topic_relation/",
                  "type=question&item_id=" +
                    data_id +
                    "&topic_title=" +
                    encodeURIComponent(
                      _topic_editor.find("#aw_edit_topic_title").val()
                    ),
                  function(result) {
                    if (result.errno != 1) {
                      AWS.alert(result.err);

                      return false;
                    }

                    _topic_editor
                      .find(".tag-bar")
                      .prepend(
                        '<span class="topic-tag" data-id="' +
                          result.rsm.topic_id +
                          '"><a href="' +
                          G_BASE_URL +
                          "/topic/" +
                          result.rsm.topic_id +
                          '" class="text">' +
                          _topic_editor.find("#aw_edit_topic_title").val() +
                          '</a><a class="close"><i class="icon icon-delete"></i></a></span>'
                      )
                      .hide()
                      .fadeIn();

                    _topic_editor.find("#aw_edit_topic_title").val("");
                  },
                  "json"
                );
                break;

              case "article":
                $.post(
                  G_BASE_URL + "/topic/ajax/save_topic_relation/",
                  "type=article&item_id=" +
                    data_id +
                    "&topic_title=" +
                    encodeURIComponent(
                      _topic_editor.find("#aw_edit_topic_title").val()
                    ),
                  function(result) {
                    if (result.errno != 1) {
                      AWS.alert(result.err);

                      return false;
                    }

                    _topic_editor
                      .find(".tag-bar")
                      .prepend(
                        '<span class="topic-tag" data-id="' +
                          result.rsm.topic_id +
                          '"><a href="' +
                          G_BASE_URL +
                          "/topic/" +
                          result.rsm.topic_id +
                          '" class="text">' +
                          _topic_editor.find("#aw_edit_topic_title").val() +
                          '</a><a class="close"><i class="icon icon-delete"></i></a></span>'
                      )
                      .hide()
                      .fadeIn();

                    _topic_editor.find("#aw_edit_topic_title").val("");
                  },
                  "json"
                );
                break;

              case "topic":
                $.post(
                  G_BASE_URL +
                    "/topic/ajax/save_related_topic/topic_id-" +
                    data_id,
                  "topic_title=" +
                    encodeURIComponent(
                      _topic_editor.find("#aw_edit_topic_title").val()
                    ),
                  function(result) {
                    if (result.errno != 1) {
                      AWS.alert(result.err);

                      return false;
                    }

                    _topic_editor
                      .find(".tag-bar")
                      .prepend(
                        '<span class="topic-tag"><a href="' +
                          G_BASE_URL +
                          "/favorite/tag-" +
                          encodeURIComponent(
                            _topic_editor.find("#aw_edit_topic_title").val()
                          ) +
                          '" class="text">' +
                          _topic_editor.find("#aw_edit_topic_title").val() +
                          '</a><a class="close"><i class="icon icon-delete"></i></a></span>'
                      )
                      .hide()
                      .fadeIn();

                    _topic_editor.find("#aw_edit_topic_title").val("");
                  },
                  "json"
                );
                break;

              case "favorite":
                $.post(
                  G_BASE_URL + "/favorite/ajax/update_favorite_tag/",
                  "item_id=" +
                    data_id +
                    "&item_type=" +
                    _topic_editor.attr("data-item-type") +
                    "&tags=" +
                    encodeURIComponent(
                      _topic_editor.find("#aw_edit_topic_title").val()
                    ),
                  function(result) {
                    if (result.errno != 1) {
                      AWS.alert(result.err);

                      return false;
                    }

                    _topic_editor
                      .find(".tag-bar")
                      .prepend(
                        '<span class="topic-tag"><a href="' +
                          G_BASE_URL +
                          "/favorite/tag-" +
                          encodeURIComponent(
                            _topic_editor.find("#aw_edit_topic_title").val()
                          ) +
                          '" class="text">' +
                          _topic_editor.find("#aw_edit_topic_title").val() +
                          '</a><a class="close"><i class="icon icon-delete"></i></a></span>'
                      )
                      .hide()
                      .fadeIn();

                    _topic_editor.find("#aw_edit_topic_title").val("");
                  },
                  "json"
                );
                break;
            }
          }
        });

        // 给编辑box取消按钮添加事件
        _topic_editor.find(".close-edit").click(function() {
          _topic_editor.removeClass("active");
          _topic_editor.find(".aw-edit-topic-box").hide();
          _topic_editor.find(".aw-edit-topic").show();
        });

        AWS.Dropdown.bind_dropdown_list(
          $(this)
            .parents(".aw-topic-bar")
            .find("#aw_edit_topic_title"),
          "topic"
        );
      }

      $(this)
        .parents(".aw-topic-bar")
        .find(".aw-edit-topic-box")
        .fadeIn();

      // 是否允许创建新话题
      if (!G_CAN_CREATE_TOPIC) {
        $(this)
          .parents(".aw-topic-bar")
          .find(".add")
          .hide();
      }

      $(this).hide();
    });
  }
};

function _t(string, replace) {
  if (typeof aws_lang != "undefined") {
    if (typeof aws_lang[string] != "undefined") {
      string = aws_lang[string];
    }
  }

  if (replace) {
    string = string.replace("%s", replace);
  }

  return string;
}

// jQuery扩展
(function($) {
  $.fn.extend({
    insertAtCaret: function(textFeildValue) {
      var textObj = $(this).get(0);
      if (document.all && textObj.createTextRange && textObj.caretPos) {
        var caretPos = textObj.caretPos;
        caretPos.text =
          caretPos.text.charAt(caretPos.text.length - 1) == ""
            ? textFeildValue + ""
            : textFeildValue;
      } else if (textObj.setSelectionRange) {
        var rangeStart = textObj.selectionStart,
          rangeEnd = textObj.selectionEnd,
          tempStr1 = textObj.value.substring(0, rangeStart),
          tempStr2 = textObj.value.substring(rangeEnd);
        textObj.value = tempStr1 + textFeildValue + tempStr2;
        textObj.focus();
        var len = textFeildValue.length;
        textObj.setSelectionRange(rangeStart + len, rangeStart + len);
        textObj.blur();
      } else {
        textObj.value += textFeildValue;
      }
    },

    highText: function(searchWords, htmlTag, tagClass) {
      return this.each(function() {
        $(this).html(
          (function high(replaced, search, htmlTag, tagClass) {
            var pattarn = search
              .replace(/\b(\w+)\b/g, "($1)")
              .replace(/\s+/g, "|");

            return replaced.replace(new RegExp(pattarn, "ig"), function(
              keyword
            ) {
              return $(
                "<" +
                  htmlTag +
                  " class=" +
                  tagClass +
                  ">" +
                  keyword +
                  "</" +
                  htmlTag +
                  ">"
              ).outerHTML();
            });
          })($(this).text(), searchWords, htmlTag, tagClass)
        );
      });
    },

    outerHTML: function(s) {
      return s
        ? this.before(s).remove()
        : jQuery("<p>")
            .append(this.eq(0).clone())
            .html();
    }
  });

  $.extend({
    // 滚动到指定位置
    scrollTo: function(type, duration, options) {
      var queue;

      if (typeof type == "object") {
        var type = $(type).offset().top;
      }

      if (options == undefined) {
        queue = true;
      } else {
        queue = options.queue;
      }

      $("html, body").animate(
        {
          scrollTop: type
        },
        {
          duration: duration ? duration : 600,
          queue: queue
        }
      );
    },
    // 日历控件
    calender: function(options) {
      return new calender(options);

      function calender(options) {
        this.options = {
          start_year: 1900,
          end_year: new Date().getFullYear(),
          year: 1970,
          month: "",
          day: "",
          year_template: [],
          month_template: [],
          day_template: []
        };

        this.options = $.extend(this.options, options);

        var _this = this;

        this._init = function() {
          this._init_year();
          this._init_month();
          this._init_day(this.options.month_el.val());
        };

        this._init_year = function() {
          if (this.options.year_el) {
            this.options.year_template.length = [];

            while (this.options.end_year > this.options.start_year) {
              this.options.year_template.push(
                '<option value="' +
                  this.options.end_year +
                  '">' +
                  this.options.end_year +
                  "</option>"
              );
              this.options.end_year--;
            }
          }

          this.options.year_el.html(this.options.year_template.join(""));

          if (this.options.year) {
            this.options.year_el.val(this.options.year);
          }

          this.options.year_el.change(function() {
            _this._init_day(_this.options.month_el.val());
          });
        };

        this._init_month = function() {
          this.options.month_template = [];

          for (var i = 1; i <= 12; i++) {
            var m = i;

            if (m < 10) {
              m = "0" + m;
            }

            this.options.month_template.push(
              '<option value="' + m + '">' + m + "</option>"
            );
          }

          this.options.month_el.html(this.options.month_template.join(""));

          if (this.options.month) {
            this.options.month_el.val(this.options.month);
          }

          this.options.month_el.change(function() {
            _this._init_day($(this).val());
          });
        };

        this._init_day = function(month) {
          var year = this.options.year_el.val(),
            max = 31;

          this.options.day_template = [];

          switch (parseInt(month)) {
            case 2:
              // 判断是否闰年
              var _year = year.substring(2);

              if (year % 4 == 0) {
                max = 29;

                if (_year == "00" && (year / 400) % 1 != 0) {
                  max = 28;
                }
              } else {
                max = 28;
              }
              break;

            case 4:
            case 6:
            case 9:
            case 11:
              max = 30;
              break;

            default:
              max = 31;
              break;
          }

          for (var i = 1; i <= max; i++) {
            var d = i;

            if (d < 10) {
              d = "0" + d;
            }

            this.options.day_template.push(
              '<option value="' + d + '">' + d + "</option>"
            );
          }

          this.options.day_el.html(this.options.day_template.join(""));

          if (this.options.day) {
            this.options.day_el.val(this.options.day);
            this.options.day = "";
          }
        };

        this._init();
      }
    }
  });
})(jQuery);
